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();
}
}
Related
I have a little problem with make a toast when my table database is null based on parsing json. I mean, when data is no result or no data found then make a toast " Sorry no data found". Any help would be greatly appreciated.
here my code for show the data
private void showEmployee(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(konfigurasi.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(konfigurasi.TAG_ID);
String nama = jo.getString(konfigurasi.TAG_NAMA);
String pyg = jo.getString(konfigurasi.TAG_PENYELENGGARA);
String tmpt = jo.getString(konfigurasi.TAG_TEMPAT);
String tgl = jo.getString(konfigurasi.TAG_TGL);
String jam = jo.getString(konfigurasi.TAG_JAM);
String email = jo.getString(konfigurasi.TAG_EMAIL);
HashMap<String,String> employees = new HashMap<>();
employees.put(konfigurasi.TAG_ID,id);
employees.put(konfigurasi.TAG_NAMA,nama);
employees.put(konfigurasi.TAG_PENYELENGGARA,pyg);
employees.put(konfigurasi.TAG_TEMPAT,tmpt);
employees.put(konfigurasi.TAG_TGL,tgl);
employees.put(konfigurasi.TAG_JAM,jam);
employees.put(konfigurasi.TAG_EMAIL,email);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new MySimpleArrayAdapter(this, list);
listView.setAdapter(adapter);
}
And this for postexcetude code :
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(TampilSemuaPgw.this,"Mengambil Data","Mohon Tunggu...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s == null || s.length() == 0){
Toast.makeText(getApplicationContext(), "No Data",Toast.LENGTH_LONG).show();
}
// Dismiss the progress dialog
if (loading.isShowing())
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
Update Code by KeLiuyue :
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if(jsonArray.length() == 0){
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
if (loading.isShowing()){
loading.dismiss();
}
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("TAG",s);
// Dismiss the progress dialog
if (loading.isShowing())
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
Try this in your code .
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
#Override
protected void onPostExecute(String s) {
// edited here
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if(jsonArray.length() == 0){
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
if (loading.isShowing()){
loading.dismiss();
}
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("TAG",s);
// Dismiss the progress dialog
if (loading.isShowing())
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
1.Determine return value whether is empty in doInBackground method
2.Determine param value whether is empty in onPostExecute method
You need to Debug this issue why your toast is not showing:
You have correctly put show Toast code in onPostExecute
Now to debug , first put a Log to know the value of s , whether it is ever null or empty.
If yes and still toast is not showing, move the dialog dismiss dialog before Toast and check.
If Toast still does not show debug your showEmployee() method as what it does.
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();
}
}
please help, I've given up on finding a solution
Data json already be in ArrayList, nothing error found but the progressdialog can't stop loading. I'm already put PG.dismis in postExecute but even the Adapter cannot changed.
private static List<DataVoucher> processResponse(String response) {
List<DataVoucher> list = new ArrayList<DataVoucher>();
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray jsonArray = jsonObj.getJSONArray("produk");
Log.d(TAG, "data lengt: " + jsonArray.length());
DataVoucher dataVoucher = null;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
dataVoucher = new DataVoucher();
dataVoucher.setKode(obj.getString("kode"));
dataVoucher.setHrg(obj.getString("hrg"));
dataVoucher.setNom(obj.getString("nom"));
dataVoucher.setKet(obj.getString("ket"));
list.add(dataVoucher);
listvoucher.add(obj.getString("nom"));
}
} catch (JSONException e) {
Log.d(TAG, e.getMessage());
}
return list;
}
public static String requestDataVoucher(final String operator) {
final String TAG = "SEND JSON";
Thread thread = new Thread() {
public void run() {
Looper.prepare();
JSONObject jsonObjSend = new JSONObject();
try {
jsonObjSend.put("type", "svoc");
jsonObjSend.put("hp", "089631633614");
jsonObjSend.put("opr", operator);
Log.i(TAG, jsonObjSend.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
SendHttpPost(jsonObjSend);
Looper.loop();
}
};
thread.start();
return TAG;
}
private class MainActivityAsync extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("retrieving...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String response = requestDataVoucher(pilihOperator
.getSelectedItem().toString());
list = processResponse(response);
return null;
}
#Override
protected void onPostExecute(String result) {
adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_item, listvoucher);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
pilihVoucher.setAdapter(adapter);
adapter.notifyDataSetChanged();
if (!adapter.isEmpty()) {
progressDialog.dismiss();
} // this is annoying
}
}
adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_spinner_item, listvoucher);
I think u mean
adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_spinner_item, list);
Btw just dismiss ur progressDialog at onPostExecute() not checking anything and maybe warn the user if the list is empty so you will evade these problems.
Many issues here
doInBackground is running in a thread, different from the ui thread. You are calling requestDataVoucher which is also creating a new thread, useless in this case.
You are calling processResponse with the String response which is the result of requestDataVoucher. According to your code, response equals "SEND JSON". So JSONObject jsonObj = new JSONObject(response); will trigger an Exception, listvoucher will remain empty, and so will your adapter. Conclusion, adapter is empty, the progressDialog won't disappear.
I can't propose a fix, as SendHttpPost is unknown. But as far as goes my understanding, you should remove the Thread creation from requestDataVoucher and return the JSON String generate by SendHttpPost.
Pls help me to parse the page! I dont mind what to do
PHP code:
[{"DATE_REG":"04.04.2014","NAME_WDAY":"\u041f`\u044f\u0442\u043d\u0438\u0446\u044f","NAME_PAIR":"3 \u043f\u0430\u0440\u0430","TIME_PAIR":"11:25-12:45""},{"DATE_REG":"04.04.2014","NAME_WDAY":"\u041f`\u044f\u0442\u043d\u0438\u0446\u044f","NAME_PAIR":"6 \u043f\u0430\u0440\u0430","TIME_PAIR":"16:35-17:55""}]
My code:
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
name2 = (TextView)findViewById(R.id.name);
para2 = (TextView)findViewById(R.id.para);
aud2 = (TextView)findViewById(R.id.aud);
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
for(int i=0; i < jsonarray.length(); i++) {
JSONObject c = new JSONObject();
// Storing JSON item in a Variable
String NAME_FIO = c.getString(prepod);
String ABBR_DISC = c.getString(para);
String NAME_AUD = c.getString(audit);
//Set JSON Data in TextView
name2.setText(NAME_FIO);
para2.setText(ABBR_DISC);
aud2.setText(NAME_AUD);
}
} catch (JSONException e) {
e.printStackTrace();
}
Your PHP is returning an array and you are attempting to parse a JSONObject from it. Change your AsyncTask and parser return types to JSONArray and use that in your onPostExecute loop.
Try this..
First you JSON is INVALID in your response one " is extra for every array element.
your JSON might like below..
[
{
"DATE_REG": "04.04.2014",
"NAME_WDAY": "П`ятниця",
"NAME_PAIR": "3 пара",
"TIME_PAIR": "11:25-12:45"
},
{
"DATE_REG": "04.04.2014",
"NAME_WDAY": "П`ятниця",
"NAME_PAIR": "6пара",
"TIME_PAIR": "16: 35-17: 55"
}
]
It's JSONArray not JSONObject try to get like below.
private class JSONParse extends AsyncTask<String, String, JSONArray> {
and
#Override
protected JSONArray doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(url);
return json;
}
then
#Override
protected void onPostExecute(JSONArray json) {
pDialog.dismiss();
try {
// Getting JSON Array
for(int i=0; i < json.length(); i++) {
JSONObject c = json.getJSONObject(i);
// Storing JSON item in a Variable
String NAME_FIO = c.getString(prepod);
String ABBR_DISC = c.getString(para);
String NAME_AUD = c.getString(audit);
//Set JSON Data in TextView
name2.setText(NAME_FIO);
para2.setText(ABBR_DISC);
aud2.setText(NAME_AUD);
}
} catch (JSONException e) {
e.printStackTrace();
}
I am having a scenario in which I am calling asynctask in onclicklistener of button. In post execute method of asynctask I am adding values in arraylist which I want to return to the method calling asynctask
This is my asynctask
public class FetchtopTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
String getitemcode=params[0];
// Building Parameters
ArrayList<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("ItemCode",getitemcode));
Log.d("request!", "starting");
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/top.php",params1);
String retstring=response.toString();
Log.d(retstring,"stringggggg");
return retstring;
}
catch(Exception io){
msg = "No Network Connection";
}
return null;
}
#Override
protected void onPostExecute(String sJson) {
try {
JSONArray aJson = new JSONArray(sJson);
for(int i=0;i<aJson.length();i++)
{
JSONObject jsonO = aJson.getJSONObject(i);
top1.add(jsonO.getString("MName"));
top2.add(jsonO.getString("Amount"));
top3.add(jsonO.getString("TaxStruct"));
}
}catch(JSONException e){
msg = "Invalid response";
}
}
}
I want to pass top1,top2,top3 arraylists to calling method
please help me to achieve this.
You may use ArrayList of ArrayLists:
ArrayList<ArrayList<String>> tops= new ArrayList<ArrayList<String>>();
tops.add(top1);
tops.add(top2);
tops.add(top3);
and
return tops;
hey Just call AsyncTask in btn Click
and in post execute method
call another method which will use that Array which is created in post Execute.
#Override
protected void onPostExecute(String sJson) {
try {
JSONArray aJson = new JSONArray(sJson);
for(int i=0;i<aJson.length();i++)
{
JSONObject jsonO = aJson.getJSONObject(i);
top1.add(jsonO.getString("MName"));
top2.add(jsonO.getString("Amount"));
top3.add(jsonO.getString("TaxStruct"));
anotherMethod(top);
}
}catch(JSONException e){
msg = "Invalid response";
}
}