I am parsing a JSON Data with Volley library and I retrieve the data in ListView but only the last value is printed.. Here is my implementation :
public void getListElem(final Context context) {
apws = new APWSManager(context, new APWSRequestState() {
#Override
public void customURLFinishedDownload(String response) {
// TODO Auto-generated method stub
Log.i("RESPONSE LISTVIEWPARSER : ", response);
try {
JSONObject json = null;
JSONArray array = new JSONArray(response);
for (int j = 0; j < array.length(); j++) {
json = array.getJSONObject(j);
Log.i("JSONOBJECT : ", json.toString());
parseJsonItem(json);
/* myItemList = new ItemObject(json.getString("title"),
json.getString("value_out"), json.getString("picture")); */
// m_ListItem.add(myItemList);
myList.setAdapter(myAdapter);
Log.i("LISTVIEW TITLE", array.getJSONObject(j).getString("title"));
Log.i("LISTVIEW VALUE", array.getJSONObject(j).getString("value_out"));
Log.i("LISTVIEW PICTURE", array.getJSONObject(j).getString("picture"));
}
myAdapter.notifyDataSetChanged();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void customURLFailedDownload(String errorMessage) {
// TODO Auto-generated method stub
Log.i("ERROR REQUEST : ", errorMessage.toString());
}
});
apws.callAPWSRequest("getnews", null, null, TypeMethod.GET, true);
}
private void parseJsonItem(JSONObject item) {
try {
ItemObject itemObject = new ItemObject(item.getString("title"), item.getString("value_out"), item.getString("picture"));
// Ici à la place tu ajoutes ton objet dans ton array
m_ListItem.add(itemObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
My ListView is printed correctly but always with the same value (the last value in json). How Can I do to retrieve each value in each item of my ListView ?
Thank you guys !
Related
I'm getting a responseJson and I'm trying to exact data to load in my grid view. I have 2 textviews in my screen and once I press 1 textview then items which belongs to SubCategoryID =1 should load. When the textview 2 is pressed then the items belongs to SubCategoryID = 2 should load.
I have given the code below,
#Override
public void onTaskCompleted(JSONArray responseJson) {
try {
final List<String> descriptions = new ArrayList<String>();
final List<String> imageUrls = new ArrayList<String>();
for (int i = 0; i < responseJson.length(); ++i) {
final JSONObject object = responseJson.getJSONObject(i);
mQuickReturnViewTop
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if ((object.getString("MainCategoryID"))
.equals("1")
&& (object
.getString("SubCategoryID"))
.equals("1")) {
Log.i("ImageURL ",
object.getString("ImageURL"));
imageUrls.add(object
.getString("ImageURL"));
Log.i("Description ",
object.getString("Description"));
descriptions.add(object
.getString("Description"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
CustomGridPizza adapter = new CustomGridPizza(
getActivity(), descriptions, imageUrls);
grid.setAdapter(adapter);
}
});
mQuickReturnViewIta
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if ((object.getString("MainCategoryID"))
.equals("1")
&& (object
.getString("SubCategoryID"))
.equals("2")) {
Log.i("ImageURL ",
object.getString("ImageURL"));
imageUrls.add(object
.getString("ImageURL"));
Log.i("Description ",
object.getString("Description"));
descriptions.add(object
.getString("Description"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
CustomGridPizza adapter = new CustomGridPizza(
getActivity(), descriptions, imageUrls);
grid.setAdapter(adapter);
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
When using this code, it loads only 1 item and when keep pressing the text view then it adds the same item one by one.
I need help to load the items to grid at once. Any help will be appreciated.
For every JSON object you are creating a new OnClickListener and overwriting the last one with the call to setOnClickListener, so basically you are always adding the last JSON object.
You need to create/set the OnClickListener and the adapter outside of the for loop.
try {
final List<String> descriptions1 = new ArrayList<String>();
final List<String> imageUrls1 = new ArrayList<String>();
final List<String> descriptions2 = new ArrayList<String>();
final List<String> imageUrls2 = new ArrayList<String>();
for (int i = 0; i < responseJson.length(); ++i) {
final JSONObject object = responseJson.getJSONObject(i);
try {
if ((object.getString("MainCategoryID"))
.equals("1")
&& (object
.getString("SubCategoryID"))
.equals("1")) {
Log.i("ImageURL ",
object.getString("ImageURL"));
imageUrls1.add(object
.getString("ImageURL"));
Log.i("Description ",
object.getString("Description"));
descriptions1.add(object
.getString("Description"));
}else if ((object.getString("MainCategoryID"))
.equals("1")
&& (object
.getString("SubCategoryID"))
.equals("2")) {
Log.i("ImageURL ",
object.getString("ImageURL"));
imageUrls2.add(object
.getString("ImageURL"));
Log.i("Description ",
object.getString("Description"));
descriptions2.add(object
.getString("Description"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mQuickReturnViewTop
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CustomGridPizza adapter = new CustomGridPizza(
getActivity(), descriptions1, imageUrls1);
grid.setAdapter(adapter);
}
});
mQuickReturnViewIta
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CustomGridPizza adapter = new CustomGridPizza(
getActivity(), descriptions2, imageUrls2);
grid.setAdapter(adapter);
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I'm having troubles deleting rows in the sqlite database.
What I'm trying to do is getting the Id's I want to delete from the Remote Database, and then use them to delete the rows in the SQLite DataBase.
But so far is not working
Here is where I first delete the items, and then insert items if needed.
// Method to Sync MySQL to SQLite DB
public void syncSQLiteMySQLDB() {
// Create AsycHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
// Http Request Params Object
RequestParams params = new RequestParams();
// Show ProgressBar
prgDialog.show();
//Llamada HTTP a getdeletes.php
client.post("http://restaurantechinaimperial.com/mysqlsqlitesync/getDeletes.php", params, new AsyncHttpResponseHandler(){
#Override
public void onSuccess(String response) {
deleteSQLite(response);
}
});
// Make Http call to getplatos.php
client.post("http://restaurantechinaimperial.com/mysqlsqlitesync/getplatos.php", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
// Hide ProgressBar
prgDialog.hide();
// Update SQLite DB with response sent by getusers.php
updateSQLite(response);
}
// When error occured
#Override
public void onFailure(int statusCode, Throwable error, String content) {
// TODO Auto-generated method stub
// Hide ProgressBar
prgDialog.hide();
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "Recurso no encontrado", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "Algo ha fallado en el servidor", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Error Inesperado! [Razon mas probable: El dispositivo no esta conectado a Internet]",
Toast.LENGTH_LONG).show();
}
}
});
}
Here is the method which call the method in the sqlitecontroller to delete.
public void deleteSQLite(String response){
try {
// Extract JSON array from the response
JSONArray arr = new JSONArray(response);
System.out.println(arr.length());
// If no of array elements is not zero
if(arr.length() != 0){
// Loop through each array element, get JSON object which has deleteid
for (int i = 0; i < arr.length(); i++) {
// Get JSON object
JSONObject obj = (JSONObject) arr.get(i);
String id=obj.getString("Id");
controller.deletePlato(id);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Here is the delete method on the sqlitehelper
public void deletePlato(String deleteid){
SQLiteDatabase database = this.getWritableDatabase();
database.delete("platos", "platoId = 'deleteid'", null);
database.close();
}
Can anybody help?
I have a api call that returns this json object:
{
"elenco": [
"folder 1",
"folder 2",
"folder 3"
],
"codice": "123456789"
}
and this is my piece of code that get the result:
protected void onPostExecute(JSONObject result) {
// Close progress dialog
Dialog.dismiss();
JSONObject jobj = null;
String codice_utente = null;
JSONArray elenco_cartelle = null;
try {
jobj = new JSONObject(String.valueOf(result));
} catch (JSONException e) {
e.printStackTrace();
}
//Provo a recuperare i campi json
try {
codice_utente = jobj.getString("codice");
elenco_cartelle = jobj.getJSONArray("elenco");
} catch (JSONException e) {
e.printStackTrace();
}
//This should fetch the elenco array
for (int i = 0; i < elenco_cartelle.length(); i++) {
JSONObject childJSONObject = null;
try {
childJSONObject = elenco_cartelle.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
//Can't use getString here...
}
}
How can I fetch the elenco part? I do not have a key to use, so how can I add every row in an ArrayList?
I tried to use a for but I have no idea about how to get the rows
Use JSONArray.getString() http://developer.android.com/reference/org/json/JSONArray.html#getString(int)
for (int i = 0; i < elenco_cartelle.length(); i++) {
String content = null;
try {
content = elenco_cartelle.getString(i);
} catch (JSONException e) {
e.printStackTrace();
}
//Can't use getString here...
}
You now have your content on content
I am working on JSON data fetching and displaying but before that I store it in Sqlite.
After fetching from that Sqlite table, it works fine when internet is available but app automatically closed when internet connection is not available. I am using hash-map custom adapter to showing data in listview. I have created a fetchdata method from SqlHelper class
protected Void doInBackground(Void... params)
{
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
int state = NetworkUtilClass.checkInternetConenction(getActivity());
if (state == 1) {
// jsonobject = new JSONObject(str1);
jsonobject = JSONFunction.getJSONfromURL("url");
JSONObject collection = null;
try {
collection = jsonobject.getJSONObject("collection");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray response = null;
try {
response = collection.getJSONArray("response");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < response.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonobject1 = null;
try {
jsonobject1 = (JSONObject) response.get(i);
noticeId = jsonobject1.getString("id").toString();
noticeTitle = jsonobject1.getString("title").toString();
noticeDescription = jsonobject1.getString("description").toString();
noticePublishedBy = jsonobject1.getString("publishedBy").toString();
noticeValidFrom = jsonobject1.getString("validFrom").toString();
noticeValidTo = jsonobject1.getString("validTo").toString();
Log.e(noticeId, "show");
Log.e(noticeTitle, "show");
Log.e(noticeDescription, "show");
//demo_database.insertData(noticeTitle,noticeDescription,noticePublishedBy,noticeValidFrom,noticeValidTo);
demo_database.insertNoticeData(noticeId,noticeTitle,noticeDescription, noticePublishedBy,
noticeValidFrom, noticeValidTo);
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else{
onPostExecute(null);
}
return null;
}
#Override
protected void onPostExecute(Void args)
{
// Locate the listview in listview_main.xml
getData();
demo_database.close();
// Close the progressdialog
mProgressDialog.dismiss();
}
}
private void getData() {
// TODO Auto-generated method stub
try {
arraylist = demo_database.fetchNoticeData();
} catch (Exception e) {
e.printStackTrace();
}
listview = (ListView) getActivity().findViewById(R.id.listview);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
Toast.makeText(getActivity(), "ListView clicked", Toast.LENGTH_SHORT).show();
}
});
// Pass the results into ListViewAdapter.java
adapter = new NoticeListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
}
}
Actually the thing is that when you are trying to access the json through url when internet is not available so the json Array with name response get no items in that so it got Null and when you try to execute For loop in which you give the length of json array it would be crash because of null pointer exception..
Your App is Crashing on the for Loop Right?
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.