I am using google api to convert feed xml to json, but when I use it on my android app it says that "03-10 22:32:08.045: E/log_tag(1456): Error parsing data org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject", this is part of my code where I am converting xml into json, can somebody help me? Thanks.
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(NoticiasMia.this);
// Set progressdialog title
//mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Actualizando...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&q=myfeedurl");
try {
// Locate the array name in JSON
if(jsonobject == null)
return null;
JSONObject subObjuno = jsonobject.getJSONObject("responseData");
JSONObject subObjdos = subObjuno.getJSONObject("feed");
jsonarray = subObjdos.getJSONArray("entries");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobjecttres = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("title", jsonobjecttres.getString("title"));
map.put("link", jsonobjecttres.getString("link"));
map.put("publishedDate", jsonobjecttres.getString("publishedDate"));
map.put("contentSnippet", jsonobjecttres.getString("contentSnippet"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
if(arraylist == null || arraylist.size() == 0){
new DownloadJSON().execute();
mProgressDialog.dismiss();
return;
}
// Locate the listview in listview_main.xml
listview = (ListView) NoticiasMia.this.findViewById(R.id.lista_faltas_cometidas);
// Pass the results into ListViewAdapter.java
adapter = new LazyAdapterNoticiasMias(NoticiasMia.this, arraylist, "fonts/Roboto-Thin.ttf", "fonts/Roboto-Medium.ttf");
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
Related
I´m trying to populate a listview with a custom adapter. How can I fix the following error:
Type mismatch: cannot convert from JSONObject to JSONArray
I have already changed the params but it didn´t work.
private class JSONParse extends AsyncTask<String, String, JSONArray> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListResult.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONArray doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
return json; // Type mismatch: cannot convert from JSONObject to JSONArray
}
#Override
protected void onPostExecute(JSONArray response) {
pDialog.dismiss();
try {
// Getting JSON Array
for(int i = 0; i < response.length(); i++){
JSONObject obj = response.getJSONObject(i);
Medico medico = new Medico();
medico.setNome(obj.getString("name"));
medico.setSobrenome(obj.getString("sname"));
unid = obj.getString("unidade");
serv = obj.getString("servico");
esp = obj.getString("espec");
if(unidade.getText().toString().equalsIgnoreCase(unid) &&
servico.getText().toString().equalsIgnoreCase(serv) &&
espec.getText().toString().equalsIgnoreCase(esp)){
mList.add(medico);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if(mList.size() > 0){
listView.setAdapter(adapter);
}else{
empty.setText("No results");
}
adapter.notifyDataSetChanged();
}
}
You are returning as JSONArray in doInBackground.
Replace the return type as JSONObject and handle it accordingly wherever it is used
Your doInBackground is passing an Object ( {} datatype) and your onPostExecute is expecting a Array ( [] datatype). The data type is mismatched.
Depends on the JSON data you are trying to process, may try change the onPostExecute to accept an JSONObject then access each properties of it:
#Override
protected void onPostExecute(JSONObjct response)
{
pDialog.dismiss();
try
{
// Getting JSON Array
for (Map.Entry<String,JsonElement> entry : response.entrySet())
{
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
So I have an Asynctask class with this codes and I just want to change the view of contents from text to html
private class JSONP extends AsyncTask<String, String, JSONObject>{
#Override
protected void onPreExecute() {
super.onPreExecute();
title=(TextView)findViewById(R.id.textView2);
content=(TextView)findViewById(R.id.txtcontent);
}
#Override
protected JSONObject doInBackground(String... arg0) {
JSONParser jp = new JSONParser();
JSONObject tempjo = jp.getjsonfromurl(url);
return tempjo;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
try {
news = result.getJSONArray(Tag_posts);
for(int i = 0;i<news.length();i++){
JSONObject c = news.getJSONObject(i);
String titles = c.getString(Tag_title);
String contents = c.getString(Tag_content);
HashMap<String, String> map = new HashMap<String, String>();
map.put(Tag_title, titles);
map.put(Tag_content, contents);
newslist.add(map);
ListAdapter list = new SimpleAdapter(MainActivity.this,
newslist,
R.layout.listv,
new String[] {Tag_title,Tag_content},
new int[]{R.id.textView2, R.id.txtcontent});
mylist.setAdapter(list);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
i know the method must be something like
textView.setText(Html.fromHtml(contents));
but i just don't know where to put this code? make another class or directly use it in my asynctask class
I am developing android application and I got a error When I parse XML data like Json.I confused how many array has this data? I share code at below. can anyone help me or sharing example code like this xml data?
public class MainActivity extends Activity implements OnRefreshListener,
OnClickListener {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
JSONArray jsonarray2;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String FLAG = "flag";
Button btngeri;
static Integer[] imageId = { R.drawable.enveloppe, R.drawable.enveloppe,
R.drawable.enveloppe, R.drawable.enveloppe, R.drawable.enveloppe,
R.drawable.enveloppe, R.drawable.enveloppe };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
btngeri = (Button) findViewById(R.id.btn_geri);
btngeri.setOnClickListener(this);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Mail Kutusu");
// Set progressdialog message
mProgressDialog.setMessage("Güncelleme Yapılıyor...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://78.186.62.169:8210/AnketServis.asmx/Message");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("MessageVO");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
// map.put("rank", jsonobject.getString("rank"));
map.put("country", jsonobject.getString("Konu"));
// map.put("population",
// jsonobject.getString("population"));
// map.put("flag", jsonobject.getString("flag"));
// 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
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist, imageId);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
Yo cannot parse xml file like json. You have to use xml parser. There are two parse method. SAX and Dom. Yo can see the versus about them.
What is the difference between SAX and DOM?
And You can see the an xml parser sample in android.
http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/
I'm new in android. I'm trying to get json but I got this error.
I trying following this tutorial http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
I already search the solution, but I still don't get it how to use the JSONArray.
Here is my Json example
[{"id":"152","category_id":"14","item_name":"Restaurant1","cuisine_id":"3","cuisine_name":"Chinese"},{"id":"161","category_id":"14","item_name":"Restaurant10","cuisine_id":"17","cuisine_name":"Middle Eastern"},{"id":"153","category_id":"14","item_name":"Restaurant2","cuisine_id":"17","cuisine_name":"Middle Eastern"},{"id":"154","category_id":"14","item_name":"Restaurant3","cuisine_id":"7","cuisine_name":"American"},{"id":"155","category_id":"14","item_name":"Restaurant4","cuisine_id":"3","cuisine_name":"Chinese"},{"id":"156","category_id":"14","item_name":"Restaurant5","cuisine_id":"8","cuisine_name":"Coffee"},{"id":"157","category_id":"14","item_name":"Restaurant6","cuisine_id":"8","cuisine_name":"Coffee"},{"id":"158","category_id":"14","item_name":"Restaurant7","cuisine_id":"17","cuisine_name":"Middle Eastern"},{"id":"159","category_id":"14","item_name":"Restaurant8","cuisine_id":"6","cuisine_name":"Indonesian"},{"id":"160","category_id":"14","item_name":"Restaurant9","cuisine_id":"3","cuisine_name":"Chinese"}]
And Here the class
/**
* Async task class to get json by making HTTP call
* */
private class GetRestaurant extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Attractions.this);
pDialog.setMessage("Please wait...");
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
restaurant = jsonObj.getJSONArray(TAG_ITEM_NAME);
// looping through All Contacts
for (int i = 0; i < restaurant.length(); i++) {
JSONObject c = restaurant.getJSONObject(i);
String id = c.getString(TAG_CUISINE_NAME);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_CUISINE_NAME, id);
// adding contact to contact list
restaurantList.add(contact);
}
} 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(
Attractions.this, restaurantList,
R.layout.attractionslayout, new String[] { TAG_ITEM_NAME, TAG_CUISINE_NAME }, new int[] { R.id.item_name,
R.id.cuisine_name});
// Assign adapter to ListView
listview.setAdapter(adapter);
}
}
Thanks Before.
Try this..
Your response starts with JSONArray
[ ==> JSONArray
{ ==> JSONObject
Change this..
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
restaurant = jsonObj.getJSONArray(TAG_ITEM_NAME);
to
restaurant = new JSONArray(jsonStr);
Your string is not json object , it is json array because the string are start via third bracket
so, try this
restaurant = new JSONArray(jsonStr);
you do not need to convert it as a josn object,
JSONObject jsonObj = new JSONObject(jsonStr);
I get the entire data from the Server by using doInBackground() method as shown below.
class DataLoader extends Activity{
public void onCreate()
{
...............................
new AsyncTask1().execute();
}
class AsyncTask1 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(DataLoader.this);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
protected String doInBackground(String... args) {
JSONObject json;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1",datafield1));
params.add(new BasicNameValuePair("param2",datafield2));
json = jsonParser.makeHttpRequest(url, "POST", params);
try {
int success = json.getInt(SUCCESS);
if (success == 1) {
products = json.getJSONArray(PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(ID);
String price = c.getString(PRICE);
String name = c.getString(NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(PID, id);
map.put(PRICE, price);
map.put(NAME, name);
..................
// adding HashList to ArrayList
productsList.add(map);
}
return "success";
}
else {
// no materials found for this section
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String msg) {
if( msg != null && msg.equals("success"))
{
progressDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
customadapter=new CustomAdapterList(DataLoader.this, productsList);
listView.setAdapter(adapter);
}
});
}
}
}
As per the above code, I am setting the data to the listview in the onPostExecute() method only after the entire data is loaded. But now I want to implement the CW Endless Adapter with the present code, but as I am new to this, I am unable to get how to move on from here. I included the CWAdapter jar file in the libs folder. Have referred this and searched a lot , but no use. Can some one please help me implementing the endless feature for the data I get?
Basic Idea is to run an AsyncTask when more data is required, that is when uses scrolls to bottom of the list. Here's a quick demo project.