Android custom adapter passing ArrayList of Objects - android

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

Related

How to clear Spinner 2 values by changing spinner 1 values

In my application i have two spinners, first spinner contains some values like (str1,str2,str3...) and my second spinner contains some value related to each value of first spinner. when i select one value from first spinner, the related values are comming in second spinner for this i done code perfectly as follows.
this is my first spinner code:
private HashMap<String,String>departmentMap=new HashMap<>();
private void loadSpinnerData(String url) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(responseString);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String department = jsonobject.getString("Department");
uid = jsonobject.getString("ID");
Department.add(department);
departmentMap.put(department,uid);
}
spinner.setAdapter(new ArrayAdapter<String>(NewDeficiency.this, android.R.layout.simple_spinner_dropdown_item, Department));
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
this is belongs to first spinner item selection:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l){
String department=spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(),department,Toast.LENGTH_LONG).show();
String id=departmentMap.get(department);
loadSpinnerDeficiency(URL2,id);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView){
// DO Nothing here
}
});
And the following is for getting proper response from spinner2:
private void loadSpinnerDeficiency(String url2,String uid) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://182.18.163.39/train/m/def.php?issue=2&dept="+uid);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(responseString);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String defcat = jsonobject.getString("Deficiency");
defid = jsonobject.getString("ID");
Deficiency.add(defcat);
}
spinner2.setAdapter(new ArrayAdapter<String>(NewDeficiency.this, android.R.layout.simple_spinner_dropdown_item, Deficiency));
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here when change my first selection in spinner one the spinner2 selected values of first selection must be clear.
But it doesn't happening please help me to solve this.
used below code ..
/**
* remove second spinner value based on first spinner selected value
* it match then remove it.
*/
private void removeValue() {
List<String> itemvalue=new ArrayList<>();
itemvalue.add("Abc");
itemvalue.add("cde");
itemvalue.add("xyz");
List<String> itemvalue2=new ArrayList<>();
itemvalue2.add("Abc");
itemvalue2.add("cde");
itemvalue2.add("xyz");
itemvalue2.add("pqr");
itemvalue2.add("stu");
Spinner spinner=findViewById(R.id.sp);
Spinner spinner1=findViewById(R.id.sptwo);
ArrayAdapter<String> adapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,itemvalue);
ArrayAdapter<String> adapter2=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,itemvalue2);
spinner.setAdapter(adapter);
spinner1.setAdapter(adapter2);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
itemvalue2.remove(spinner.getSelectedItem());
adapter2.notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}

OnPostExecute item to ListView

Here is OnPostExecute That retuns Listitem [name1,name2,name3]:
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String result = json.getString(KEY_SUCCESS);
if (Integer.parseInt(result) == 1) {
pDialog.setMessage("Loading View");
pDialog.setTitle("Getting Friends");
//JSONArray root = new JSONArray(json);
JSONArray friend = json.getJSONArray("users");
List<String> item = new ArrayList<String>();
for (int i = 0; i < friend.length(); i++) {
JSONObject att = (JSONObject) friend.getJSONObject(i);
String res = att.getString("username");
item.add(res);
}
SharedPreferences FriendList = getSharedPreferences("FriendList", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = FriendList.edit();
edit.putString("KEY_FRIENDS", item.toString());
edit.commit();
} else {
pDialog.dismiss();
}
}else {
pDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
pDialog.dismiss();
}
I want it In List View but im stucked, because i cant use ListAdapter in OnPostExecute.
public class FriendList extends ListActivity { ...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_friend_list);
// listt = (TextView) findViewById(R.id.testyL);
// list = (TextView) findViewById(R.id.textView4);
// list = (ListView) findViewById(R.id.label);
try {
new GetFriends().execute();
}catch (Exception e) {
e.printStackTrace() ;
Log.e("ERR ", "AsyncTASK" + e.toString());
}
SharedPreferences FriendList = getSharedPreferences("FriendList", Context.MODE_PRIVATE);
String u = FriendList.getString("KEY_FRIENDS", "0");
I tried to put item to SharedPref but it seems i dont know how to properly retrevie it and conter to variable that can be used by Array/List Adapter.
Here is the problem :)
// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, item ));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), Logged.class);
// sending data to new activity
i.putExtra("friend", product);
startActivity(i);
}
});
}
Change GetFriends constructor add reference to FriendList object:
try {
new GetFriends(FriendList.this).execute();
}catch (Exception e) {
e.printStackTrace() ;
Log.e("ERR ", "AsyncTASK" + e.toString());
}
class:
public class GetFriends extends [...]{
private ListActivity mList;
public GetFriends(ListActivity list){
mList = list;
}
[...]
#Override
protected void onPostExecute(JSONObject json) {
//set Adapter to list
mList.
}
}

How to add some parsed JSON objects into a custom listview?

Well, I don't know if the title is clear, so now I'll explain everything better.
I have parsed some JSON objects. After parsing, I need to show them into a custom listview.
The JSON objects are correctly parsed into string, because I have first show them into common textviews (just for a test).
Also the custom listview is working, because I have first added some values "manually" (again, just for testing it).
Here my problem:
Now I want to add the JSON objects (parsed into string) into my custom listview. I've tried every "tip and trick" I know, unsuccessfully. After two days of working, I've decided to ask you.
Before posting the code: the http request for parsing JSON objects is made with this library.
Here the code
Getprofiledata.java
public class Getprofiledata extends ActionBarActivity {
String num;
Boolean ok=true;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data);
String url = "URL FOR JSON OBJECTS";
ListView listadata = (ListView) findViewById(R.id.listadata);
final List<Data> datalist = new LinkedList <Data>();
AsyncHttpClient client = new AsyncHttpClient();
client.get(url,new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
ok=true;
i=1;
num = Integer.toString(i);
while(ok==true){
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject object = jsonObject.getJSONObject(num);
/*********
* THESE ARE THE STRINGS I NEED TO ADD TO MY CUSTOM LISTVIEW
*********/
String record1 = object.getString("first");
String record2 = object.getString("second");
String record3 = object.getString("third");
String record4 = object.getString("fourth");
String record5 = object.getString("fiveth");
i++;
num = Integer.toString(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ok=false;
}
}
}
#Override
public void onFailure(Throwable e,String response) {
Log.d("AREQ","http GET request failed");
}
});
/*********
* HERE WE CAN ADD VALUES TO MY CUSTOM LISTVIEW
* HOW CAN I PASS THE PREVIOUS STRING IN THIS STATEMENT?
*
* THIS IS THE METHOD:
* datalist.add(new Data(record1,record2,record3,record4,record5));
*********/
//HERE THE ADAPTER FOR MY CUSTOM LISTVIEW
Getprofiledata_customadapter adapter = new Getprofiledata_customadapter(this, R.layout.data_riga, datalist);
listadata.setAdapter(adapter);
}
}
I hope I've been clear. Can you help me? I'm desperate! :(
Thanks in advance
Edit: here my Getprofiledata_customadapter.java
public class Getprofiledata_customadapter extends ArrayAdapter<Data>{
public Getprofiledata_customadapter(Context context, int textViewResourceId,
List <Data> objects) {
super(context, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.data_riga, null);
TextView firstrecord = (TextView)convertView.findViewById(R.id.tv1);
TextView secondrecord = (TextView)convertView.findViewById(R.id.tv2);
TextView thirdrecord = (TextView)convertView.findViewById(R.id.tv3);
TextView forthrecord = (TextView)convertView.findViewById(R.id.tv4);
TextView fivethrecord = (TextView)convertView.findViewById(R.id.tv5);
Data c = getItem(position);
firstrecord.setText(c.getRecord1());
secondrecord.setText(c.getRecord2());
thirdrecord.setText(c.getRecord3());
forthrecord.setText(c.getRecord4());
fivethrecord.setText(c.getRecord5());
return convertView;
}
}
Basically you just pre-create the List first. Then with that data create an adapter and set it to your ListView.
At the moment you just loop through the data without saving it at all.
It would look something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data);
mListView = (ListView) findViewById(R.id.listadata);
String url = "URL FOR JSON OBJECTS";
AsyncHttpClient client = new AsyncHttpClient();
client.get(url,new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
ok=true;
i=1;
num = Integer.toString(i);
while(ok==true){
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject object = jsonObject.getJSONObject(num);
/*********
* THESE ARE THE STRINGS I NEED TO ADD TO MY CUSTOM LISTVIEW
*********/
String record1 = object.getString("first");
String record2 = object.getString("second");
String record3 = object.getString("third");
String record4 = object.getString("fourth");
String record5 = object.getString("fiveth");
// Save strings to your list
mData.add(new Data(record1,record2,record3,record4,record5));
i++;
num = Integer.toString(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ok=false;
}
}
// When the data loop is over create the adapter and set it to your ListView
Getprofiledata_customadapter adapter = new Getprofiledata_customadapter(this,
R.layout.data_riga, mData);
mListView.setAdapter(adapter);
}
#Override
public void onFailure(Throwable e,String response) {
Log.d("AREQ","http GET request failed");
}
});
}

JSON array to auto complete text view in 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/

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