I am developing android app in that i want to display json data in listview with load more button, but when i click load more button old data is replaceing by new one i want both and old and new data to be displayed.Lihstview should show all data whats wrong in the code below
public class Newjava extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
CustomAdapter1 adapter2;
CustomAdapter1 adapter;
ProgressDialog mProgressDialog;
ArrayList<FeedAddress> arraylist;
String url = "http://xxxx.vdv.com/api/fvn/page1";
String arraymovie = "all";
public String string;
ListView listView;
int i = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.list);
arraylist = new ArrayList<FeedAddress>();
// Retrive JSON Objects from the given website URL in
// JSONfunctions.class
jsonobject = JSONfunctions.getJSONfromURL(url);
try {
// Locate the array name
JSONObject jsonObject1 = jsonobject.getJSONObject("appname");
jsonarray = jsonObject1.getJSONArray("kfnh");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject post = (JSONObject) jsonarray.getJSONObject(i);
FeedAddress map = new FeedAddress();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.setMovieName(post.getString("movieName"));
map.setName(post.getString("movieActors"));
map.setMovieId(post.getString("movieId"));
String imageUrl = "http://www.xxhbc.com/upload/dv/thumbnail/"
+ post.getString("moviePhoto")
+ post.getString("moviePhotoExt");
map.setImageUrl(imageUrl);
System.out.println("ldhslhdljh " + imageUrl);
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
Button btnLoadMore = new Button(this);
btnLoadMore.setText("Load More");
// Adding Load More button to lisview at bottom
listView.addFooterView(btnLoadMore);
// Getting adapter
adapter = new CustomAdapter1(this, arraylist);
listView.setAdapter(adapter);
/**
* Listening to Load More button click event
* */
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Starting a new async task
i += 1;
new DownloadJSON().execute();
}
});
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(Newjava.this);
// Set progressdialog title
mProgressDialog.setTitle("APP Name");
mProgressDialog.setIcon(R.drawable.ic_launcher);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
arraylist = new ArrayList<FeedAddress>();
// Retrive JSON Objects from the given website URL in
// JSONfunctions.class
String URL = "http://zvzvs.vczx.com/api/v/page"
+ i;
System.out.println("new url " + URL);
jsonobject = JSONfunctions.getJSONfromURL(URL);
try {
// Locate the array name
JSONObject jsonObject1 = jsonobject
.getJSONObject("fvvzx");
jsonarray = jsonObject1.getJSONArray("allmovies");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject post = (JSONObject) jsonarray.getJSONObject(i);
FeedAddress map = new FeedAddress();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.setMovieName(post.getString("movieName"));
// map.setName(post.getString("movieActors"));
map.setMovieId(post.getString("movieId"));
String imageUrl = "http://www.vsv.com/upload/vc/thumbnail/"
+ post.getString("moviePhoto")
+ post.getString("moviePhotoExt");
map.setImageUrl(imageUrl);
System.out.println("ldhslhdljh " + imageUrl);
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
int currentPosition = listView.getFirstVisiblePosition();
// Appending new data to menuItems ArrayList
adapter = new CustomAdapter1(Newjava.this, arraylist);
listView.setAdapter(adapter);
// Setting new scroll position
listView.setSelectionFromTop(currentPosition + 1, 0);
updateList(string);
}
}
public void updateList(final String string) {
// TODO Auto-generated method stub
listView.setVisibility(View.VISIBLE);
// mProgressDialog.dismiss();
listView.setAdapter(new CustomAdapter1(Newjava.this, arraylist));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(),"position[]" ,
// Toast.LENGTH_SHORT).show();
Object o = listView.getItemAtPosition(position);
FeedAddress newsData = (FeedAddress) o;
System.out.println("hgsh " + string);
System.out.println("next " + newsData.getMovieId());
Intent intent = new Intent(Newjava.this,
SingleMenuItemActivity.class);
intent.putExtra("feed", newsData.getMovieId());
intent.putExtra("actor", newsData.getName());
startActivity(intent);
}
});
}
}
It replaces data because you recreate adapter every time. You should create adapter once and then add to it more data, not recreate it.
Related
I cant send all the rows of list view,Every time just last row of list view is going to the server,i want send all the items of list view when i click place order button.here is edited code my full code:
public class Order_From_App_All_new extends Activity implements View.OnClickListener {
ProgressDialog mProgressDialog
ArrayList<Actor> productlist = new ArrayList<>();
TextView txt1;
Button order;
ListView listview;
ImageView ivImage;
EditText edt2;
String address;
TextView txt17;
int position;
String product_id;
String product_qty;
ListView listview1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.orderfromapp);
listview = (ListView) findViewById(R.id.listView1);
order=(Button)findViewById(R.id.button4);
edt2=(EditText)findViewById(R.id.editText2);
ListView listview = (ListView) findViewById(R.id.listView1);
adapter = new Product_Adapter(Order_From_App_All_new.this, R.layout.row1, productlist);
listview.setAdapter(adapter);
new DownloadJSON().execute();
order.setOnClickListener(this);
}
// #Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
product_name = (String) mySpinner.getSelectedItem();
String product_quantity = edt1.getEditableText().toString();
String addtocartquerystring = "?product_name=" + product_name + "&product_quantity=" + product_quantity;
Log.d("Request : ", "starting 00 " + CC14.GETURL17 + addtocartquerystring);
new GetAddToCart(this, CC14.GETURL17 + addtocartquerystring).execute();
break;
case R.id.button4:
address=edt2.getEditableText().toString();
String[] productid = new String[productlist.size()];
String[] productquantity = new String[productlist.size()];
for (int i = 0; i < productlist.size(); i++) {
productid[i]=productlist.get(i).getProductid();
productquantity[i]=productlist.get(i).getProductquantity();
product_qty=productquantity[i];
product_id=productid[i];
}
String placeorderquerystring = "?address=" + address + "&product_id=" + product_id+"&product_qty="product_qty;
Log.d("Request : ", "starting 00 " + CC14.GETURL23 + placeorderquerystring);
new GetPlaceOrder(Order_From_App_All_new.this, CC14.GETURL23 + placeorderquerystring).execute();
break;
default:
break;
}
}
public class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Locate the WorldPopulation Class
// productlist = new ArrayList<>();
// Create an array to populate the spinner
spinnerlist = new ArrayList<String>();
// JSON file URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://duraent.net/android_order_app/api/android/orderList.php");
try {
// Locate the NodeList name
jsonarray = jsonobject.getJSONArray("product");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
spinnerlist.add(jsonobject.optString("productname"));
// Actor actors = new Actor();
// actors.setProductname("Productname", jsonobject.optString("Productname"));
// actors.setDirectmobileorderprice("directmobileorderprice", jsonobject.getString("directmobileorderprice"));
// productlist.add(actors);
//Populate spinner with country names
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the spinner in activity_main.xml
Spinner mySpinner = (Spinner) findViewById(R.id.spinner2);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(Order_From_App_All_new.this,
android.R.layout.simple_spinner_dropdown_item,
spinnerlist));
}
}
public class GetAddToCart extends AsyncTask<String, String, String> {
Http_OrderFromAppNew request = new Http_OrderFromAppNew();
Context ctx;
ListView listview;
TextView txt1;
String latLong_url;
ProgressDialog pd;
private String json;
public GetAddToCart(Context _ctx, String _latong_url) {
ctx = _ctx;
latLong_url = _latong_url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(Order_From_App_All_new.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
// Locate the WorldPopulation Class
// Create an array to populate the spinner
// spinnerlist = new ArrayList<String>();
// JSON file URL address
String json = request
.makeHttpRequest(latLong_url, "GET", null);
// Populate spinner with country names
Log.d("Request Login attempt", json.toString());
return json;
}
#Override
protected void onPostExecute(String json) {
// Locate the spinner in activity_main.xml
//adapter.notifyDataSetChanged();
try {
JSONObject jsonobject = new JSONObject(json);
// Locate the NodeList name
jsonarray = jsonobject.getJSONArray("product");
for (int i = 0; i < jsonarray.length(); i++) {
try {
jsonobject = jsonarray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
// spinnerlist.add(jsonobject.optString("productname"));
Actor actors = new Actor();
actors.setProductname("productname",jsonobject.getString("productname"));
actors.setProductid("productid",jsonobject.getString("productid"));
actors.setSellingprice("sellingprice",jsonobject.getString("sellingprice"));
actors.setPricetotal("pricetotal", jsonobject.getString("pricetotal"));
actors.setProductquantity("productquantity", jsonobject.getString("productquantity"));
productlist.add(actors);
adapter.changeData(productlist);
// ListView listview = (ListView) findViewById(R.id.listView1);
//adapter = new Product_Adapter(getApplicationContext(), R.layout.row1, productlist);
//adapter.notifyDataSetChanged();
//listview.setAdapter(adapter);
mProgressDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class GetPlaceOrder extends AsyncTask<String, String,String> {
Http_OrderFromAppNew request = new Http_OrderFromAppNew();
Context ctx;
ListView listview;
TextView txt1;
String latLong_url;
ProgressDialog pd;
private String json;
public GetPlaceOrder(Context _ctx, String _latong_url) {
ctx = _ctx;
latLong_url = _latong_url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(Order_From_App_All_new.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
// Locate the WorldPopulation Class
// Create an array to populate the spinner
// spinnerlist = new ArrayList<String>();
// JSON file URL address
String json = request
.makeHttpRequest(latLong_url, "GET", null);
// Populate spinner with country names
Log.d("Request Login attempt", json.toString());
return json;
}
#Override
protected void onPostExecute(String json) {
// Locate the spinner in activity_main.xml
//adapter.notifyDataSetChanged();
try {
TextView txt17=(TextView)findViewById(R.id.textView17);
txt17.append(json);
mProgressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The few lines doing the sending should be inside the for loop:
for (int i = 0; i < productlist.size(); i++) {
productid[i]=productlist.get(i).getProductid();
productquantity[i]=productlist.get(i).getProductquantity();
product_qty=productquantity[i];
product_id=productid[i];
String placeorderquerystring = "?address=" + address + "&product_id=" + product_id+"&product_qty="product_qty;
Log.d("Request : ", "starting 00 " + CC14.GETURL23 + placeorderquerystring);
new GetPlaceOrder(Order_From_App_All_new.this, CC14.GETURL23 + placeorderquerystring).execute();
}
You need to send the cart items as an JSON obj or array to server,
{
"Customer":"Name",
"cart":"Cart ID",
"date":"10-06-2016",
"time":"3.36",
"cartItems":[
{
"ProductID":"1",
"ProductQuantity":"3"
},
{
"ProductID":"2",
"ProductQuantity":"5"
},
{
"ProductID":"6",
"ProductQuantity":"4"
}
]
}
To get the above format, use the following code
private String getItems() {
JSONObject dataObj = new JSONObject();
try {
dataObj.putOpt("Customer", "Name");
dataObj.putOpt("cart", "Cart ID");
dataObj.putOpt("date", "DATE");
dataObj.putOpt("time", "TIME");
JSONArray cartItemsArray = new JSONArray();
JSONObject cartItemsObjedct;
for (int i = 0; i < cartItems.size(); i++) {
cartItemsObjedct = new JSONObject();
cartItemsObjedct.putOpt("ProductID", cartItems.get(i).getId);
cartItemsObjedct.putOpt("ProductQuantity", cartItems.get(i).getProductQuantity);
cartItemsArray.put(cartItemsObjedct);
}
dataObj.put("cartItems", cartItemsArray);
} catch (JSONException e) { // TODO Auto-generated catch bloc
e.printStackTrace();
}
return dataObj.toString();
}
So I'm stuck on this... I need to display images in a listview which gets its data from a json file.
I've already setup the connection, parsed the json file and displayed what i need. But somehow I can't find much information about how to turn a string (which has the URL) into an image in a listview.
The string which has the url is called "ImageLink"
Below is my MainActivity.
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get game info JSON
private static String url = "https://dl.dropboxusercontent.com/u/38379784/Upcoming%20Games/DataForUPG.js";
// JSON Node names
private static final String TAG_Games = "games";
private static final String TAG_Title = "Title";
private static final String TAG_Description = "Description";
private static final String TAG_Release = "Release";
private static final String TAG_ImageLink = "ImageLink";
// Gameinfo JSONArray
JSONArray games = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> GamesList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GamesList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String Title = ((TextView) view.findViewById(R.id.Title))
.getText().toString();
String Description = ((TextView) view.findViewById(R.id.Description))
.getText().toString();
String Release = ((TextView) view.findViewById(R.id.Release))
.getText().toString();
String ImageLink = ((TextView) view.findViewById(R.id.ImageLink_label))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleListItem.class);
in.putExtra(TAG_Title, Title);
in.putExtra(TAG_Description, Description);
in.putExtra(TAG_Release, Release);
in.putExtra(TAG_ImageLink, ImageLink);
startActivity(in);
}
});
// Calling async task to get json
new GetGames().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetGames extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Data...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
games = jsonObj.getJSONArray(TAG_Games);
// looping through All games
for (int i = 0; i < games.length(); i++) {
JSONObject c = games.getJSONObject(i);
String Title = c.getString(TAG_Title);
String Description = c.getString(TAG_Description);
String Release = c.getString(TAG_Release);
String ImageLink = c.getString(TAG_ImageLink);
// tmp hashmap for single game
HashMap<String, String> games = new HashMap<String, String>();
// adding each child node to HashMap key => value
games.put(TAG_Title, Title);
games.put(TAG_Description, Description);
games.put(TAG_Release, Release);
games.put(TAG_ImageLink, ImageLink);
// adding contact to gameinfo list
GamesList.add(games);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, GamesList,
R.layout.list_item, new String[] { TAG_Title, TAG_Release,
TAG_Description, TAG_ImageLink }, new int[] { R.id.Title,
R.id.Release, R.id.Description, R.id.ImageLink_label });
setListAdapter(adapter);
}
}
}
I would appreciate any help
Well, you could probably create another async task to handle downloading the image like this:
private class DownloadImg extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
String TAG_ImageLink = params[0];
Bitmap bm = null;
try {
InputStream in = new java.net.URL(TAG_ImageLink).openStream();
bm = BitmapFactory.decodeStream(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
#Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
or you could use a 3rd party image loading library like picasso or volley's ImageRequest
im writing an app for a site which uses JSON API. Im trying to parse the JSON but i get:
Error parsing data org.json.JSONException: Value error of type
java.lang.String cannot be converted to JSONArray
This is due its a string, i've tried other methods but i can only get information from the first string, because each string has its own randomly generated "filename/id", you can take a look at the json output:
{"error":"","S8tf":{"infoToken":"wCfhXe","deleteToken":"gzHTfGcF","size":122484,"sha1":"8c4e2bbc0794d2bd4f901a36627e555c068a94e6","filename":"Screen_Shot_2013-07-02_at_3.52.23_PM.png"},"S29N":{"infoToken":"joRm6p","deleteToken":"IL5STLhq","size":129332,"sha1":"b4a03897121d0320b82059c36f7a10a8ef4c113d","filename":"Stockholmsyndromet.docx"}}
Im trying to get it to show both of the "objects" from the json string. How can i make a lopp for it to find all the items or simply make it list all the "objects" contained in the "error" identifier?
My Main Activity:
public class FilesActivity extends SherlockListActivity implements
OnClickListener {
private ProgressDialog mDialog;
ActionBar ABS;
TextView session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dblist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Files");
TextView txt = (TextView)findViewById(R.id.nodata);
/**String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = null;
try {
jObject = new JSONObject(s);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject menu = null;
try {
menu = jObject.getJSONObject("menu");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Map<String,String> map = new HashMap<String,String>();
Iterator<String> iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = null;
try {
value = menu.getString(key);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
map.put(key,value);
txt.setText(value);
} **/
JsonAsync asyncTask = new JsonAsync();
// Using an anonymous interface to listen for objects when task
// completes.
asyncTask.setJsonListener(new JsonListener() {
#Override
public void onObjectReturn(JSONObject object) {
handleJsonObject(object);
}
});
// Show progress loader while accessing network, and start async task.
mDialog = ProgressDialog.show(this, getSupportActionBar().getTitle(),
getString(R.string.loading), true);
asyncTask.execute("http://api.bayfiles.net/v1/account/files?session=" + PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("sessionID", "defaultStringIfNothingFound"));
//session = (TextView)findViewById(R.id.textView1);
//session.setText(PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("sessionID", "defaultStringIfNothingFound"));
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
private void handleJsonObject(JSONObject object) {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String files = null;
try {
int id;
String name;
JSONArray array = new JSONArray("error");
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
id = row.getInt("id");
name = row.getString("name");
}
//JSONArray shows = object.getJSONArray("");
/*String shows = object.getString("S*");
for (int i = 0; i < shows.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
//JSONObject e = shows.getJSONObject(i);
files = shows;
//map.put("video_location", "" + e.getString("video_location"));
//TextView txt = (TextView)findViewById(R.id.nodata);
//txt.setText(files);
mylist.add(map); *
}*/
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.dbitems,
new String[] { files, "video_location" }, new int[] { R.id.item_title,
R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
//Intent myIntent = new Intent(ListShowsController.this,
// TestVideoController.class);
//myIntent.putExtra("video_title", o.get("video_title"));
//myIntent.putExtra("video_channel", o.get("video_channel"));
//myIntent.putExtra("video_location", o.get("video_location"));
//startActivity(myIntent);
}
});
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
Any help is much appreciated!
You're trying to get the error field as a JSONArray. Its a string. You can't process a string as an array, it throws that exception. In fact, I don't see any arrays in there at all.
I would look into using a JSon library like Gson (https://code.google.com/p/google-gson/). You are able to deserialize collections, which is much easier than doing it yourself.
I am unable to display images but the text is displayed.
I have modified the code from http://mobile.dzone.com/news/android-tutorial-how-parse to the code below.
I would prefer using SimpleAdapter only .Is it possible? As I have implemented the same code as below everywhere.
Or little modifications to the below code would be fine.
How do I display images?
public class MainActivity extends ListActivity {
ArrayList<HashMap<String, String>> mylist;
SimpleAdapter adapter;
ProgressDialog pd ;
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
mylist = new ArrayList<HashMap<String, String>>();
new loadingDisplayClass().execute();
}
public class loadingDisplayClass extends AsyncTask<String, Integer, String> {
protected void onPreExecute() {
pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Loading......");
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String url = "https://itunes.apple.com/us/rss/topalbums/limit=50/json";
JSONObject json = JSONfunctions.getJSONfromURL(url);
try {
JSONObject arr2 = json.getJSONObject("feed");
JSONArray arr = arr2.getJSONArray("entry");
for (int i = 0; i < arr.length(); i++) {
JSONObject e1 = arr.getJSONObject(i);
JSONArray jsar = e1.getJSONArray("im:image");
JSONObject jsname = e1.getJSONObject("im:name");
String name = jsname.getString("label");
JSONObject jso = e1.getJSONObject("im:artist");
String lbl = jso.getString("label");
JSONObject e12 = jsar.getJSONObject(0);
String icon = e12.getString("label");
HashMap<String, String> hashmapnew = new HashMap<String, String>();
hashmapnew.put("icons", icon);
hashmapnew.put("name", name);
hashmapnew.put("artist", lbl);
mylist.add(hashmapnew);
publishProgress(((int) ((i + 1 / (float) arr.length()) * 100)));
}
} catch (JSONException e) {
Toast.makeText(getBaseContext(),
"Network communication error!", 5).show();
}
adapter = new SimpleAdapter(getBaseContext(), mylist,
R.layout.list, new String[] {
"icons","name","artist" },
new int[] { R.id.image,R.id.name,R.id.artist });
return null;
}
protected void onProgressUpdate(Integer... integers) {
pd.incrementProgressBy(integers[0]);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
setListAdapter(adapter);
pd.dismiss();
lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
}
});
}
}
}
I am unable to display images but the text is displayed
Images won't display because you are just passing url to the SimpleAdapter.In order to show images you need to first download the images in the url returned above service .
You need to create a custom Adapter and display images by downloading them
Downloading each image and displaying image in imageView takes lot time and as the listview recycle views your images will always download when the list is scrolled. So what you need to do is to use -Universal-Image-Loader or Lazy List to provide automatic downloading and caching images.
I am trying to retrieve values from a json api and displaying then in a listView. The listView contains 3 elements and I am also implementing onItemClickListner() and when an Item is clicked it will display a detailed view related to that item. I am using an ArrayList to store all the json values. Now I want to retrieve a value from that ArrayList so that the OnClickListner() will get that value and from that value the detailed view will be displayed..
I am using AsyncTask to retrieve all the json values
#Override
protected String doInBackground(String... DATA) {
if(rqst_type.equals("top5"))
{
String url = DATA[1];
JsonParser jParser = new JsonParser();
JSONObject json = jParser.getJSONfromUrl(url);
try
{
JSONArray top5 = json.getJSONArray(TAG_TOP5);
public static ArrayList<HashMap<String, String>> top5List = new ArrayList<HashMap<String, String>>();
top5List.clear();
for(int i=0; i<top5.length(); i++)
{
Log.v(TAG_LOG, "Value of i: "+String.valueOf(i));
JSONObject t = top5.getJSONObject(i);
course_id = t.getString(TAG_CRSID);
created_date = t.getString(TAG_CRTDATE);
golfcourse_name = t.getString(TAG_GLFCRSNAME);
facilities = t.getString(TAG_FCLTY);
holes = t.getString(TAG_HOLES);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_CRSID, course_id);
map.put(TAG_CRTDATE, created_date);
map.put(TAG_GLFCRSNAME, golfcourse_name);
map.put(TAG_FCLTY, facilities);
map.put(TAG_HOLES, holes);
top5List.add(map);
Log.v(LoadingScreen.TAG_LOG, "top5List: "+String.valueOf(top5List));
}
}
catch(JSONException e)
{
Log.v(TAG_LOG, String.valueOf(e));
}
}
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(rqst_type.equals("top5"))
{
Intent in = new Intent(context, MyTop5.class);
in.putExtra(TAG_CRSID, course_id);
in.putExtra(TAG_CRTDATE, created_date);
in.putExtra(TAG_GLFCRSNAME, golfcourse_name);
in.putExtra(TAG_FCLTY, facilities);
in.putExtra(TAG_HOLES, holes);
Log.v(TAG_LOG, "Valuse to MyTop5: "+course_id+" "+created_date+" "+golfcourse_name+" "+
facilities+" "+holes);
context.startActivity(in);
}
This is the file to where I am displaying the list and the onItenClickListner()..
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.my_top5);
Intent in = getIntent();
golfcourse_name = in.getStringExtra(TAG_GLFCRSNAME);
course_id = in.getStringExtra(TAG_CRSID);
created_date = in.getStringExtra(TAG_CRTDATE);
facilities = in.getStringExtra(TAG_FCLTY);
holes = in.getStringExtra(TAG_HOLES);
Log.v(LoadingScreen.TAG_LOG, "course id: "+String.valueOf(course_id));
ListAdapter adapter = new SimpleAdapter(this, LoadingScreen.top5List, R.layout.top5_list,
new String[] { TAG_GLFCRSNAME, TAG_CRSID, TAG_CRTDATE, TAG_FCLTY, TAG_HOLES },
new int[] { R.id.top_golfname, R.id.top_courseid, R.id.top_createdate, R.id.top_fclty, R.id.top_holes });
setListAdapter(adapter);
Log.v(LoadingScreen.TAG_LOG, "course id: "+String.valueOf(course_id));
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String url = "http://mygogolfteetime.com/iphone/viewdeal/127";
new LoadingScreen(MyTop5.this).execute("view_detail", url);
}
});
}
In the given URL I want to change the 127 to the value which is stored in the top5List.
String url = "http://mygogolfteetime.com/iphone/viewdeal/127";
The value I am trying to find in the top5List is the value of "course_id"
Thanks in advance..
top5List.get(your position).get(your Key);
With this code you can find the value on which you want to change.