JSON array to auto complete text view in android - android

i am working on an android app where i have to parse a Json array and adapt it to an auto complete text view. I am getting correct response from my server, since i am a fresher to android and Json parsing i am not getting how to parse that json array to array adapter and add it to auto complete text view.
Can any body suggest me how to do it..?
Response as follows.
[
{
city: "bng",
area: "anagar",
id: 510000032
},
{
city: "bng",
area: "bnagar",
id: 510000021
},
{
city: "bng",
area: "cnagar",
id: 510000037
}
]
i want area to be matched in my auto complete text view.
I created auto complete text view in my layout file.
This is how i am trying
public class MainActivity extends Activity {
List<String> responseList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AutoCompleteTextView auto1 = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
new HttpGetTask().execute();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_expandable_list_item_2, responseList);
auto1.setAdapter(adapter);
}
private class HttpGetTask extends AsyncTask<Void, Void, String> {
String URL = "http://xyz/cities.json?app_id=test";
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected String doInBackground(Void... params) {
HttpGet request = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
return mClient.execute(request, responseHandler);
} catch (ClientProtocolException exception) {
exception.printStackTrace();
} catch (IOException exception) {
exception.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray json = new JSONArray(result);
Log.v("ResponseCity", result);
responseList = new ArrayList<String>();
for (int i = 0; i < json.length(); i++) {
final JSONObject e = json.getJSONObject(i);
String name = e.getString("area");
responseList.add(name);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (null != mClient)
mClient.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Any suggestions are appreciated...

Add the response string into a List<String> like this
List<String> responseList = new ArrayList<String>();
for (int i = 0; i < json.length(); i++) {
final JSONObject e = json.getJSONObject(i);
String name = e.getString("area");
responseList.add(name);
}
Now, you can set the response list to AutoCompleteTextView like this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, responseList);
AutoCompleteTextView textView = (AutoCompleteTextView)
findViewById(R.id.autoCompleteTextView1);
textView.setAdapter(adapter);

Android AutoCompleteTextView Example using JSON with source code.
here is the examples :
https://developers.google.com/places/training/autocomplete-android
http://manishkpr.webheavens.com/android-autocompletetextview-example-json/

Related

How to set Assets json file data in two spinner + android?

Json File:
{
"Iraq":["Baghdad","Karkh","Sulaymaniyah","Kirkuk","Erbil","Basra","Bahr","Tikrit","Najaf","Al Hillah","Mosul","Haji Hasan","Al `Amarah","Basere","Manawi","Hayat"],
"Lebanon":["Beirut","Zgharta","Bsalim","Halba","Ashrafiye","Sidon","Dik el Mehdi","Baalbek","Tripoli","Baabda","Adma","Hboub","Yanar","Dbaiye","Aaley","Broummana","Sarba","Chekka"]
}
I need to display country name in first spinner and city name in second spinner as per selected countries of spinner.
How to code it android?
My Code:
public class Search_for_room extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ArrayList<String> worldlist;
ArrayList<CollegeList> world;
String value,key;
List<String> al;
ArrayAdapter<String> adapter;
HashMap<String, String> m_li = new HashMap<String, String>();
public ArrayList<SpinnerModel> CustomListViewValuesArr = new ArrayList<SpinnerModel>();
CustomAdapterStatus customAdapter;
Search_for_room activity = null;
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_for_room);
activity = this;
ArrayList<String> items=getCountries("countriesToCities.json");
spinner=(Spinner)findViewById(R.id.spCountry);
spinnerCity=(Spinner)findViewById(R.id.spCity);
}
private ArrayList<String> getCountries(String fileName){
JSONArray jsonArray=null;
ArrayList<String> cList=new ArrayList<String>();
try {
InputStream is = getResources().getAssets().open(fileName);
int size = is.available();
byte[] data = new byte[size];
is.read(data);
is.close();
String json = new String(data, "UTF-8");
JSONObject jsonObj = new JSONObject(json);
// JSONObject resultObject = jsonObj.getJSONObject("result");
System.out.print("======Key: "+jsonObj);
Iterator<String> stringIterator = jsonObj.keys();
while(stringIterator.hasNext()) {
key = stringIterator.next();
value = jsonObj.getString(key);
System.out.println("------------"+key);
m_li.put(key,value);
al = new ArrayList<String>(m_li.keySet());
final SpinnerModel sched = new SpinnerModel();
/******* Firstly take data in model object ******/
sched.setCountryName(value);
// sched.setImage(key);
sched.setStates(key);
/******** Take Model Object in ArrayList **********/
CustomListViewValuesArr.add(sched);
Resources res = getResources();
customAdapter = new CustomAdapterStatus(activity, R.layout.spinner_item, CustomListViewValuesArr,res);
spinner.setAdapter(adapter);
}
}catch (JSONException ex){
ex.printStackTrace();
/*jsonArray=new JSONArray(json);
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jobj = jsonArray.getJSONObject(i);
System.out.pri
//cList.add(String.valueOf(jobj.keys()));
}
}*/
}catch (IOException e){
e.printStackTrace();
}
return cList;
}
}
try this code it can help you
try {
// load json from assets
JSONObject obj = new JSONObject(loadJSONFromAsset());
// than get your both json array
JSONArray IraqArray = obj.getJSONArray("Iraq");
JSONArray LebanonArray = obj.getJSONArray("Lebanon");
// declare your array to store json array value
String Iraq[] = new String[IraqArray.length()];
String Lebanon[] = new String[LebanonArray.length()];
//get json array of Iraq
for (int i = 0; i < IraqArray.length(); i++) {
Iraq[i] = IraqArray.getString(i);
}
//get json array of Lebanon
for (int i = 0; i < LebanonArray.length(); i++) {
Lebanon[i] = LebanonArray.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
ask me in case of any query
add menu item in spinner
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/spinner"
android:title="Select Week"
app:actionViewClass="android.widget.Spinner"
android:textColor="#android:color/white"
android:textSize="11dp"
app:showAsAction="always" />
</menu>
add your json to array list
public void onPostExecute(String response) {
try {
list.clear();
MatchData vid = null;
Gson gson = new Gson();
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("items");
for (int i = 0; i < array.length(); i++) {
vid = gson.fromJson(array.getJSONObject(i).toString(), MatchData.class);
list.add(vid);
}
matchDataAdapter = new MatchDataAdapter(MainActivity.this, list);
mRecyclerView.setAdapter(matchDataAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
finally set adapter to spinner
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.android_action_bar_spinner_menu, menu);
MenuItem item = menu.findItem(R.id.spinner);
Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);
**ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lists);**
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected = (String) parent.getSelectedItem();
Toast.makeText(getApplicationContext(),selected,Toast.LENGTH_LONG).show();
week = Integer.parseInt(selected);
requestforinfo();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return true;
}
You had done everything correct uptil now. Just make my suggestion and you are good to go with long list of JSON data.
First make the JSON Response of file accessible to whole activity/fragment by declaring at top.
Added following function to retrieve cityList of particular country:
private ArrayList<String> getCityList(String countryName){
ArrayList<String> cityList = new ArrayList<>();
//Here jsonObj is the your JSON response from the file.
try {
JSONArray jArray =jsonObj.getJSONArray(countryName);
for(int i=0;i<jArray.length();i++){
cityList.add(jArray.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
return cityList;
}
Then add on spinnerItemSelected call the below function:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected = ((SpinnerModel) parent.getSelectedItem()).getCountryName();
//For sake of your answer I had used String Array and ArrayAdapter. You can modify as you want.
ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(YourActivity.this, R.layout.single_textview,getCityList(selected));
spinnerCity.setAdapter(cityAdapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

how to send all the list view items to the server in android

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();
}

AutoCompleteTextView - An exception occured during performFiltering()!

I'm having some issues building a AutoCompleteTextView.
I'm trying to show some Json Data inside a AutoCompleteTextView but is not working.
I'm receiving those errors when I try to write something:
W/Filter(13081): An exception occured during performFiltering()!
W/Filter(13081): java.lang.NullPointerException at java.util.ArrayList.<init>(ArrayList.java:93)
W/Filter(13081): at android.widget.ArrayAdapter$ArrayFilter.performFiltering(ArrayAdapter.java:457)
W/Filter(13081): at android.widget.Filter$RequestHandler.handleMessage(Filter.java:234)
Here, my Json Data
{"results":[{"id":"1","name":"Aveiro"},{"id":"2","name":"Beja"},{"id":"3","name":"Braga"}]}
My code:
public class MainActivity extends Activity {
List<String> responseList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AutoCompleteTextView auto1 = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
new HttpGetTask().execute();
}
private class HttpGetTask extends AsyncTask<Void, Void, String> {
String URL = "http://192.168.1.70/example/suggestion.php?name=";
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected String doInBackground(Void... params) {
HttpGet request = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
return mClient.execute(request, responseHandler);
} catch (ClientProtocolException exception) {
exception.printStackTrace();
} catch (IOException exception) {
exception.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray json = new JSONArray(result);
Log.v("ResponseCity", result);
List<String> responseList = new ArrayList<String>();
for (int i = 0; i < json.length(); i++) {
final JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
responseList.add(name);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (null != mClient)
mClient.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_dropdown_item_1line, responseList);
AutoCompleteTextView textView = (AutoCompleteTextView)
findViewById(R.id.autoCompleteTextView1);
textView.setAdapter(adapter);
}
}
}
What am I doing wrong? Thanks.
What is happening is that a JSONException is thrown leaving responseList uninitialized. The JSONException is because of this line
JSONArray json = new JSONArray(result);
The api call is returning a JSONObject, not a JSONArray. To fix the NPE, move List<String> responseList = new ArrayList<String>(); before the try block. This way, if you don't change anything else, you will provide an empty dataset. The app will not crash (at least with the same stacktrace)

Android custom adapter passing ArrayList of Objects

hopefully someone can point me in the right direction, i am creating a custom adapter to display 3 items in a listview image,id,text.
so i get my data from a webservice returning JSON objects which works fine. my problem is im not sure where im going wrong after the Asynctask because the list does not have any data, i have implemented this already when passing single field to a spinner but just can't figure it out. i know the custom adapter works as when i manually assign new CallOut objects and add to the Arraylist they list displays fine thanks for any help.
public class ListCallOuts extends Activity {
ArrayList<CallOut> callOutResults=new ArrayList<CallOut>(); //=GetCallOuts();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
GetCallOuts();
//ArrayList<CallOut> searchResults = GetSearchResults();
final ListView lv1 = (ListView) findViewById(R.id.listView1);
lv1.setAdapter(new CallOutAdapter(this,callOutResults));
//lv1.setAdapter(new CallOutAdapter(this, searchResults));
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv1.getItemAtPosition(position);
CallOut fullObject = (CallOut)o;
Toast.makeText(ListCallOuts.this, "You have chosen: " + " " +
fullObject.getName(), Toast.LENGTH_LONG).show();
}
});
}
private void GetCallOuts() {
new DownloadCallouts().execute(new String[]
{"http://192.168.0.16:8080/return_callouts.json"});
}
private class DownloadCallouts extends AsyncTask<String,Void,JSONArray> {
#Override
protected JSONArray doInBackground(String... urls) {
JSONArray array = null;
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
HttpEntity entity = execute.getEntity();
String data = EntityUtils.toString(entity);
array = new JSONArray(data);
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return array;
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
for(int i=0;i<jsonArray.length();i++){
try {
JSONObject row = jsonArray.getJSONObject(i);
CallOut callOut = new
CallOut(row.getString("id"),row.getString("customer_name")) ;
callOutResults.add(callOut);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
Change this:
final ListView lv1 = (ListView) findViewById(R.id.listView1);
lv1.setAdapter(new CallOutAdapter(this,callOutResults));
With this:
final ListView lv1 = (ListView) findViewById(R.id.listView1);
callOutAdapter = new CallOutAdapter(this,callOutResults);
lv1.setAdapter(callOutAdapter);
Note: you should define this as a property of your class to reach it at onPostExecute method.
CallOutAdapter callOutAdapter;
And after updating your arraylist at onPostExecute add this line:
callOutAdapter.notifyDataSetChanged();

Getting: Error parsing data when i get response from JSON

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.

Categories

Resources