I have a DisplayStudentName.java file which is my main activity file. There is a model class which is used to get and set data and a MyCustomAdapter.java file which extends ArrayAdapter for listview functioning.
The checkbox is clicked but value is not added in the arraylist(named data; type String).
DisplayStudentName.java
public class DisplayStudentNames extends AppCompatActivity {
String myJSON;
private static final String TAG_RESULTS = "result";
private static final String TAG_ROLL = "RollNo";
private static final String TAG_NAME = "Name";
JSONArray peoples = null;
ListView list;
ArrayList<String> checkedValue;
Button b1;
MyCustomAdapter dataAdapter = null;
ArrayList<Student> personList=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_student_names);
final Spinner sbranch = (Spinner) findViewById(R.id.branch);
final Spinner ssemester = (Spinner) findViewById(R.id.semester);
final Spinner ssubject = (Spinner) findViewById(R.id.edit_subject);
//String branch=sbranch.getSelectedItem().toString();
//String semester=ssemester.getSelectedItem().toString();
//String subject=ssubject.getSelectedItem().toString();
String branch = "cs";
String semester = "7";
String subject = "Soft Computing";
b1 = (Button) findViewById(R.id.submit);
list = (ListView) findViewById(R.id.listView);
new DataFetch().execute(branch, semester, subject);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Student student = (Student) parent.getItemAtPosition(position);
String Name = student.getName();
//String s=(String) ((TextView) view.findViewById(R.id.roll)).getText();
Toast.makeText(getApplicationContext(), "Clicked: " + Name, Toast.LENGTH_SHORT).show();
}
});
//submitAttendance();
}
class DataFetch extends AsyncTask<String, String, String> {
ArrayList<NameValuePair> params;
private ProgressDialog pDialog;
private String url_fetch_data = "http://192.168.1.4/AttendanceApp/fetch_data.php";
InputStream is = null;
String res = "";
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
String branch = args[0];
String semester = args[1];
String subject1 = args[2];
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_fetch_data);
params = new ArrayList<NameValuePair>(3);
params.add(new BasicNameValuePair("branch", branch));
params.add(new BasicNameValuePair("semester", semester));
params.add(new BasicNameValuePair("subject", subject1));
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder total = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
total.append(line);
}
String result = total.toString();
return result;
} catch (Exception e1) {
res = "error:" + e1.getMessage().toString();
e1.printStackTrace();
}
return res;
}
protected void onPostExecute(String httpResponse) {
myJSON = httpResponse;
showList();
}
}
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray("result");
personList = new ArrayList<Student>();
for (int i = 0; i < peoples.length(); i++) {
Student student = new Student();
JSONObject c = peoples.getJSONObject(i);
String roll = c.getString(TAG_ROLL);
String name = c.getString(TAG_NAME);
student.setName(name);
student.setRollNo(roll);
personList.add(student);
}
dataAdapter = new MyCustomAdapter(this, R.layout.list_item, personList);
list.setAdapter(dataAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
MyCustomAdapter.java
public class MyCustomAdapter extends ArrayAdapter {
public ArrayList<Student> personList=null;
private Context context=null;
private static LayoutInflater inflater=null;
private ArrayList<String> data=null;
private View vi;
ViewHolder holder=null;
public MyCustomAdapter(Context context, int resource, ArrayList<Student> personList) {
super(context, resource, personList);
this.context=context;
this.personList=personList;
}
private class ViewHolder{
TextView roll;
TextView name;
CheckBox check;
}
public View getView(int position, View convertView, ViewGroup parent){
Log.v("ConvertView", String.valueOf(position));
if(convertView==null){
LayoutInflater vi = (LayoutInflater)context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_item, null);
holder=new ViewHolder();
holder.roll=(TextView)convertView.findViewById(R.id.roll);
holder.name=(TextView)convertView.findViewById(R.id.name);
holder.check=(CheckBox)convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
}
else{
holder=(ViewHolder)convertView.getTag();
}
Student student=personList.get(position);
holder.roll.setText(student.getRollno());
holder.name.setText(student.getName());
holder.check.setTag(student);
holder.check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
data.add(holder.check.getText().toString());
} else {
data.remove(holder.check.getText().toString());
}
}
});
return convertView;
}
}
Student.java -Model class
public class Student {
String rollno;
String name;
Boolean checkbox;
public Student(){
}
public Student(String rollno, String name, Boolean status){
super();
this.rollno=rollno;
this.name=name;
this.checkbox=status;
}
public String getRollno(){
return rollno;
}
public void setRollNo(String rollno){
this.rollno=rollno;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public Boolean isCheckbox(){
return checkbox;
}
public void setCheckbox(boolean checkbox) {
this.checkbox= checkbox;
}
Please tell me what is wrong with my code?
}
Whenever you are making any change in the dataset, call notifyDataSetChanged().
Thus it will be like this:
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
data.add(holder.check.getText().toString());
} else {
data.remove(holder.check.getText().toString());
}
notifyDataSetChanged();
}
Related
I am using ViewPager in my app and fetch the data(Images) from server(with JSON). Even if runs smoothly no image is shown in the viewpager.
I read so many tutorial regarding this, but nobody solve my problem. Please tell me where i am wrong...
Here is my code:
view_pager.xml
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="40dp" />
image_view.xml
<ImageView
android:id="#+id/image_adapter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"/>
ViewPager_Adapter.java
public class ViewPager_Adapter extends PagerAdapter {
private String urls;
private LayoutInflater inflater;
private Context context;
ArrayList<String> mylist;
public ViewPager_Adapter(Context context, ArrayList<String> mylist) {
this.context = context;
this.urls = urls;
this.mylist = mylist;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return mylist.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.image_view, null);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image_adapter);
Glide.with(context)
.load(mylist.get(position))
.into(imageView);
view.addView(imageLayout,0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
}
View_Pager.Java
public class View_Pager extends Fragment {
private static ViewPager mPager;
JSONArray responsearray = null;
String imageOne;
private static final String TAG_PHOTO_ONE = "Gallery_Full";
ArrayList<String> myList;
HashMap<String, String> get;
ViewPager_Adapter viewpager_adapter;
LinearLayout addimages;
int REQUEST_CODE = 100;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.view_pager, null);
mPager = view.findViewById(R.id.viewpager);
new GetImages().execute(true);
return view;
}
class GetImages extends AsyncTask<Boolean, Void, String> {
#Override
protected String doInBackground(Boolean... booleans) {
ImageApi imageApi = new ImageApi();
String result = null;
try {
result = imageApi.galleryget(sharedPreferences.getString("id", ""));
JSONObject object = new JSONObject(result);
if (object.getString("error").equalsIgnoreCase("false")) {
responsearray = object.getJSONArray("response");
return "true";
} else {
String errormsg = object.getString(result);
return errormsg;
}
} catch (ApiException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
if (s.equalsIgnoreCase("true")) {
showList(responsearray);
}
}
}
}
public void showList(final JSONArray responsearray) {
try {
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList = new ArrayList<>();
myList.add(String.valueOf(get));
}
viewpager_adapter = new ViewPager_Adapter(getActivity(), myList);
String test = String.valueOf(myList);
String imgpath = getString(R.string.imgpath);
String finalimgpath = imgpath + imageOne;
Log.e("FINALPATH", finalimgpath);
} catch (JSONException e) {
e.printStackTrace();
}
mPager.setAdapter(viewpager_adapter);
viewpager_adapter.notifyDataSetChanged();
}
}
Use this code for showList() as you are not populating you're arrayList properly the data is being over write in one position .
So , what you have to do is initialize it out side of for loop .
public void showList(final JSONArray responsearray) {
try {
//here
myList = new ArrayList<>();
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList.add(String.valueOf(get));
}
viewpager_adapter = new ViewPager_Adapter(getActivity(), myList);
String test = String.valueOf(myList);
String imgpath = getString(R.string.imgpath);
String finalimgpath = imgpath + imageOne;
Log.e("FINALPATH", finalimgpath);
} catch (JSONException e) {
e.printStackTrace();
}
mPager.setAdapter(viewpager_adapter);
viewpager_adapter.notifyDataSetChanged();
}
Edit
Also if your final image path is as below then you have to update your code in adapter for image path as follow.
Update position in view.addView() too.
String test = String.valueOf(mylist.get(position));
String imgpath = getString(R.string.imgpath);
String finalimgpath = imgpath + test;
Glide.with(context)
.load(finalimgpath)
.into(imageView);
view.addView(imageLayout,position);
return imageLayout;
In your For loop you are initialising your list everytime
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList = new ArrayList<>(); // THIS IS WRONG. don't initialise every time
myList.add(String.valueOf(get)); // THIS IS ALSO WRONG. you are adding hashmap object to list
}
So make your for loop like this
myList = new ArrayList<>();
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList.add(imageOne);
}
How can i get a single column using using android. instead of getting everything from the database. i want to get only the column where full_name="john".
DataParser.jave
public class DataParser extends AsyncTask<Void,Void,Integer>{
Context c;
ListView lv;
String jsonData;
ProgressDialog pd;
ArrayList<Person> persons=new ArrayList<>();
public DataParser(Context c, ListView lv, String jsonData) {
this.c = c;
this.lv = lv;
this.jsonData = jsonData;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Parse");
pd.setMessage("Parsing...Please wait");
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parseData();
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
if(result==0)
{
Toast.makeText(c,"Unable to parse",Toast.LENGTH_SHORT).show();
}else {
//CALL ADAPTER TO BIND DATA
CustomAdapter adapter=new CustomAdapter(c,persons);
lv.setAdapter(adapter);
}
}
private int parseData()
{
try {
JSONArray ja=new JSONArray(jsonData);
JSONObject jo=null;
persons.clear();
Person s=null;
for(int i=0;i<ja.length();i++) {
jo = ja.getJSONObject(i);
int id = jo.getInt("id");
String name = jo.getString("full_name");
String sex = jo.getString("sex");
String location = jo.getString("location");
s = new Person();
s.setId(id);
s.setFull_name(name);
s.setSex(sex);
s.setLocation(location);
persons.add(s);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
Downloader.java
public class Downloader extends AsyncTask<Void,Void,String> {
Context c;
String urlAddress;
ListView lv;
ProgressDialog pd;
public Downloader(Context c, String urlAddress, ListView lv) {
this.c = c;
this.urlAddress = urlAddress;
this.lv = lv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Fetch");
pd.setMessage("Fetching....Please wait");
pd.show();
}
#Override
protected String doInBackground(Void... params) {
return this.downloadData();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
if(s==null)
{
Toast.makeText(c,"Unsuccessfull,Null
returned",Toast.LENGTH_SHORT).show();
}else
{
//CALL DATA PARSER TO PARSE
DataParser parser=new DataParser(c,lv,s);
parser.execute();
}
}
private String downloadData()
{
HttpURLConnection con=Connector.connect(urlAddress);
if(con==null)
{
return null;
}
InputStream is=null;
try {
is=new BufferedInputStream(con.getInputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line=null;
StringBuffer response=new StringBuffer();
if(br != null)
{
while ((line=br.readLine()) != null)
{
response.append(line+"\n");
}
br.close();
}else
{
return null;
}
return response.toString();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is != null)
{
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
Connector.java
public class Connector {
public static HttpURLConnection connect(String urlAddress)
{
try {
URL url=new URL(urlAddress);
HttpURLConnection con= (HttpURLConnection) url.openConnection();
//SET PROPS
con.setRequestMethod("GET");
con.setConnectTimeout(20000);
con.setReadTimeout(20000);
con.setDoInput(true);
return con;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Person.java
public class Person {
int id;
String full_name, sex, location;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFull_name() {
return full_name;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
Context c;
ArrayList<Person> persons;
LayoutInflater inflater;
public CustomAdapter(Context c, ArrayList<Person> persons) {
this.c = c;
this.persons = persons;
//INITIALIE
inflater= (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return persons.size();
}
#Override
public Object getItem(int position) {
return persons.get(position);
}
#Override
public long getItemId(int position) {
return persons.get(position).getId();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView==null)
{
convertView=inflater.inflate(R.layout.model,parent,false);
}
TextView nameTxt= (TextView) convertView.findViewById(R.id.nameTxt);
TextView sexTxt= (TextView) convertView.findViewById(R.id.propellantTxt);
TextView locationTxt= (TextView) convertView.findViewById(R.id.descTxt);
nameTxt.setText(persons.get(position).getFull_name());
sexTxt.setText(persons.get(position).getSex());
locationTxt.setText(persons.get(position).getLocation());
//ITEM CLICKS
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(c,persons.get(position).getFull_name(),Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}
server side php file
<?php
$host = 'localhost';
$username='root';
$pwd ='';
$db ='user';
$con=mysqli_connect($host,$username,$pwd,$db) or die('Unable to connect');
if(mysqli_connect_error($con))
{
echo "Failed to Connect to Database ".mysqli_connect_error();
}
$query=mysqli_query($con,"SELECT * FROM person");
if($query)
{
while($row=mysqli_fetch_array($query))
{
$data[]=$row;
}
print(json_encode($data));
}else
{
echo('Not Found ');
}
mysqli_close($con);
?>
mainactivity.java
public class MainActivity extends AppCompatActivity {
String urlAddress="http://localhost/Android/includes/retrive.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ListView lv= (ListView) findViewById(R.id.lv);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Downloader d=new Downloader(MainActivity.this,urlAddress,lv);
d.execute();
}
});
}
}
Got the code online and cant find a way to get a single column
It looks like the json you are using is from an API response. In that case, if you want to do it in SQL you would need to create a new api and SQL query on the server. If you want to just limit what is displaying in the loop, only parse the parts you want.
for(int i=0;i<ja.length();i++) {
jo = ja.getJSONObject(i);
int id = jo.getInt("id");
String name = jo.getString("full_name");
s = new Person();
s.setFull_name(name);
persons.add(s);
}
You would then need to also change the logic in your activity that displays the data, and only display person.name, as the rest of the properties will be null.
I recommend doing more research on consuming APIs and parsing JSON, as it appears that the code you are using does not have a database or SQL.
Trying to parse using jackson through intent data and adding to pojo class and getting back but not able to send and fetch ?
MainActivity is..
public class MainActivity extends AppCompatActivity {
private Button getButton;
private TextView textView;
private String jsonData;
#Override
protected void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.activity_json);
super.onCreate(savedInstanceState);
getButton = (Button) findViewById(R.id.getButton);
textView = (TextView) findViewById(R.id.textView);
getButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
new JSONTask().execute("http://192.168.11.75/Headspire/api.php");
}
});
}
public class JSONTask extends AsyncTask<String, String, String>
{
private String json_string = "";
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
InputStream stream = urlConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
while ((json_string = reader.readLine()) != null) {
buffer.append(json_string);
}
return buffer.toString();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
textView.setText(result);
jsonData = result;
}
}
public void parseJSON(View view)
{
if (jsonData == null)
{
Toast.makeText(getApplicationContext(),
"Get JSON data first", Toast.LENGTH_SHORT).show();
}
else
{
Intent intent = new Intent(this, ActivityListView.class);
intent.putExtra("json_data", jsonData);
startActivity(intent);
}
}
}
Here this is my ActivityListView class...
public class ActivityListView extends AppCompatActivity
{
private String jsonData;
private ListView listView;
private PersonAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_list_view);
listView = (ListView) findViewById(R.id.listView);
adapter = new PersonAdapter(this, R.layout.row);
listView.setAdapter(adapter);
jsonData = getIntent().getExtras().getString("json_data");
ObjectMapper mapper = new ObjectMapper();
try
{
PersonModel model = mapper.readValue(jsonData, PersonModel.class);
model.getName();
model.getId();
model.getDescription();
model.getRating();
adapter.add(model);
}
catch (JsonParseException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
My PersonAdapeter class looks like this
public class PersonAdapter extends ArrayAdapter
{
private List list = new ArrayList();
public PersonAdapter(Context context, int resource) {
super(context, resource);
}
#SuppressWarnings("unchecked")
public void add(PersonModel object)
{
super.add(object);
list.add(object);
}
#Override
public int getCount()
{
return list.size();
}
#Override
public Object getItem(int position)
{
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row;
row = convertView;
NameHolder nameHolder;
if (row == null)
{
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.row, parent, false);
nameHolder = new NameHolder();
nameHolder.nameTextView = (TextView) row.findViewById(R.id.nameTextView);
nameHolder.idTextView = (TextView) row.findViewById(R.id.idTextView);
nameHolder.descriptionTextView = (TextView) row.findViewById(R.id.descriptionTextView);
nameHolder.ratingTextView = (TextView) row.findViewById(R.id.ratingTextView);
row.setTag(nameHolder);
}
else {
nameHolder = (NameHolder)row.getTag();
}
PersonModel model = (PersonModel) this.getItem(position);
nameHolder.nameTextView.setText(model.getName());
nameHolder.idTextView.setText(model.getId());
nameHolder.descriptionTextView.setText(model.getDescription());
nameHolder.ratingTextView.setText(model.getRating());
return row;
}
static class NameHolder
{
TextView nameTextView, idTextView, descriptionTextView, ratingTextView;
}
}
Here it is my PersonModel class...
#JsonIgnoreProperties(ignoreUnknown=true)
public class PersonModel extends AppCompatActivity
{
private String name;
private String id;
private String description;
private String rating;
public PersonModel(String name, String id, String description,
String rating)
{
this.name = name;
this.id = id;
this.description = description;
this.rating = rating;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
#Override
public String toString()
{
return "PersonModel [name=" + name + ", id=" + id + ",
description=" + description + ", " +
"rating=" + rating +"]";
}
}
I have an async task which populates a spinner with data. The spinner data comes from objects in a list. My problem is when I set the onclick listener for the items in the list I also want the id from the object not just the name:
public class PortfolioGetAllLists extends AsyncTask<String, Void, String> {
Context c;
PortfolioGetAllBeers.OnArticleSelectedListener useThis;
private ProgressDialog Dialog;
public PortfolioGetAllLists (Context context, PortfolioGetAllBeers.OnArticleSelectedListener thisListener)
{
c = context;
useThis = thisListener;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting Brewery List");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
final ListView lv = (ListView) ((Activity) c).findViewById(R.id.allYourBeersList);
//make array list for beer
final List<String> tasteList = new ArrayList<String>();
tasteList.add("");
for(int i = 0; i < jsonArray.length(); i++) {
String bID = jsonArray.getJSONObject(i).getString("id");
String beer = jsonArray.getJSONObject(i).getString("name");
String rate = "na";
String beerID = "na";
//create object
ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID, bID);
//add to arraylist
tasteList.add(beer);
}
// Selection of the spinner
Spinner spinner = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
// Application of the Array to the Spinner
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(c, android.R.layout.simple_spinner_item,tasteList );
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);
//add on item selected
final Spinner portfolioType = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String portfolioChoice = portfolioType.getSelectedItem().toString();
//Toast.makeText(((Activity) c).getApplicationContext(), portfolioChoice, Toast.LENGTH_LONG).show();
lv.setAdapter(null);
//get brewery beers
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
try {
portfolioChoice = URLEncoder.encode(portfolioChoice, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//construct url
String url = "myURL";
Log.d("portfolio", url);
//async task goes here
//new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);
PortfolioGetAllBeers task = new PortfolioGetAllBeers(c);
task.setOnArticleSelectedListener(useThis);
task.execute(url);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
This line below is the line which get the beers name, but I do not know how to get also the id from the object which sets the listview name:
String portfolioChoice = portfolioType.getSelectedItem().toString();
Update:
I have changed my above code to this to incorporate a custom adapter:
public class PortfolioGetAllLists extends AsyncTask<String, Void, String> {
Context c;
PortfolioGetAllBeers.OnArticleSelectedListener useThis;
private ProgressDialog Dialog;
public PortfolioGetAllLists (Context context, PortfolioGetAllBeers.OnArticleSelectedListener thisListener)
{
c = context;
useThis = thisListener;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting Brewery List");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
final ListView lv = (ListView) ((Activity) c).findViewById(R.id.allYourBeersList);
//make array list for beer
final List<ShortBeerInfo> tasteList = new ArrayList<ShortBeerInfo>();
//tasteList.add("");
for(int i = 0; i < jsonArray.length(); i++) {
String bID = jsonArray.getJSONObject(i).getString("id");
String beer = jsonArray.getJSONObject(i).getString("name");
String rate = "na";
String beerID = "na";
//create object
ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID, bID);
//add to arraylist
tasteList.add(tempTaste);
}
// Selection of the spinner
Spinner spinner = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
// Application of the Array to the Spinner
ShortBeerInfoAdapter<ShortBeerInfo> spinnerArrayAdapter = new ArrayAdapter<ShortBeerInfo>(c, android.R.layout.simple_spinner_item,tasteList );
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);
//add on item selected
final Spinner portfolioType = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String portfolioChoice = portfolioType.getSelectedItem().toString();
//Toast.makeText(((Activity) c).getApplicationContext(), portfolioChoice, Toast.LENGTH_LONG).show();
lv.setAdapter(null);
//get brewery beers
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
try {
portfolioChoice = URLEncoder.encode(portfolioChoice, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//construct url
String url = "myURL";
Log.d("portfolio", url);
//async task goes here
//new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);
PortfolioGetAllBeers task = new PortfolioGetAllBeers(c);
task.setOnArticleSelectedListener(useThis);
task.execute(url);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
but on this line:
ShortBeerInfoAdapter<ShortBeerInfo> spinnerArrayAdapter = new ArrayAdapter<ShortBeerInfo>(c, android.R.layout.simple_spinner_item,tasteList );
I am getting shortbeerinfoadapter does not have type parameters
my short beer info adapter is:
public class ShortBeerInfoAdapter extends ArrayAdapter<ShortBeerInfo> {
Context context;
int layoutResourceId;
List<ShortBeerInfo> data = null;
public ShortBeerInfoAdapter(Context context, int layoutResourceId, List<ShortBeerInfo> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
beerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new beerHolder();
holder.txtBeer = (TextView)row.findViewById(R.id.breweryName);
holder.txtRate = (TextView)row.findViewById(R.id.breweryRate);
holder.txtBar = (RatingBar) row.findViewById(R.id.starbar);
row.setTag(holder);
}
else
{
holder = (beerHolder)row.getTag();
}
ShortBeerInfo beer = data.get(position);
holder.txtBeer.setText(beer.beer);
holder.txtRate.setText(beer.rate + " out of 5.00 Stars");
holder.numHolder= Float.parseFloat(beer.rate);
holder.txtBar.setNumStars(5);
holder.txtBar.setRating(holder.numHolder);
return row;
}
static class beerHolder
{
TextView txtBeer;
TextView txtRate;
RatingBar txtBar;
Float numHolder;
}
}
You have your ShortBeerInfo, which includes the name and ID. You take the beer name, add it to a list of strings, then create the ArrayAdapter from that list. The ArrayAdapter only contains the names.
To get the ID you will need a custom array adapter of type ShortBeerInfo. You'll need to override OnCreateView in the adapter to create the View object for the list item that only contains the beer name. (Or any other beer info you may want to display)
Then in your selection listener getSelectedItem will return a ShortBeerInfo, containing the ID of the selected beer.
I'm making an app and I have an activity called SearchActivity. I have two custom ListViews and one works well. My problem is the list used with AdapterEventos. When I start the app nothing appears in this list.
The data from this list is added from a Post (DescarregarEventos method) and I think the problem is because the ArrayAdapter eventos is empty. If you see my code [1], the log that I print before the setAdapter of this list returns empty.
Does somebody know how I can fix this?
[1] http://pastebin.com/FZacCrHD
Thanks
EDIT:
I'm already see that POST returns the all data requested.
RELEVANT CODE:
public class SearchActivity extends ListActivity {
public ArrayList<Evento> eventos = new ArrayList<Evento>();
static final String TAG = "AsyncTaskParseJson.java";
static final HttpClient httpclient = new DefaultHttpClient();
public class Evento {
public String nome;
public String local;
public String inicio;
public Evento(String nome, String local, String inicio) {
this.nome = nome;
this.local = local;
this.inicio = inicio;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getLocal() {
return local;
}
public void setLocal(String local) {
this.local = local;
}
public String getInicio() {
return inicio;
}
public void setInicio(String inicio) {
this.inicio = inicio;
}
}
public class AdapterEventos extends ArrayAdapter<Evento> {
private final Context context;
private final ArrayList<Evento> eventosArrayList;
public AdapterEventos(Context context, ArrayList<Evento> eventos) {
super(context, R.layout.listeventos, eventos);
this.context = context;
this.eventosArrayList = eventos;
}
public View getViewEventos(int position, View convertView, ViewGroup parent) {
//Create inflater
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Get rowView from inflater
View LinhaEventoView = inflater.inflate(R.layout.listeventos, parent, false);
//Get the text view from the rowView
TextView nomeView = (TextView) LinhaEventoView.findViewById(R.id.tvNomeEvento);
TextView localView = (TextView) LinhaEventoView.findViewById(R.id.tvLocalEvento);
TextView inicioView = (TextView) LinhaEventoView.findViewById(R.id.tvInicioEvento);
//Set the text for textView
nomeView.setText(eventosArrayList.get(position).getNome());
localView.setText(eventosArrayList.get(position).getLocal());
inicioView.setText(eventosArrayList.get(position).getInicio());
//return rowView
return LinhaEventoView;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.search_activity);
new DescarregarEventos().execute();
ListView ListEventos=(ListView)findViewById(R.id.listEventos);
Log.d("eventos","eventos: " + eventos);
ListEventos.setAdapter(new AdapterEventos(this, eventos));
public class DescarregarEventos extends AsyncTask<String, String, String> {
JSONArray dataJsonArr = null;
protected String doInBackground(String... arg) {
HttpPost httppost = new HttpPost(eventosUrl);
String evt = null;
try {
//Criar parĂ¢metros para o Post.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("eventos", "data"));
httppost.setEntity(new UrlEncodedFormEntity(params));
//Executar o Post.
ResponseHandler<String> responseHandler = new BasicResponseHandler();
evt = httpclient.execute(httppost, responseHandler);
} catch (UnsupportedEncodingException e) {
Log.d("HTTP","ERRO A ADICIONAR OS PARĂ‚METROS PARA O POST EM \"DescarregarEventos()\"");
e.printStackTrace();
} catch (IOException e) {
Log.d("HTTP", "ERRO EM \"DescarregarEventos()\"");
e.printStackTrace();
}
return evt;
}
// Tratar a resposta do Post e adicionar ao array respetivo.
public void onPostExecute(String evt) {
try {
JSONArray E = new JSONArray(evt);
for (int i = 0; i < E.length(); i++) {
JSONObject evento = E.getJSONObject(i);
eventos.add(new Evento(evento.getString("nome"),evento.getString("localizacao"),evento.getString("data_inicio")));
}
} catch (JSONException e) {
Log.d("HTTP","ERRO A TRATAR OS EVENTOS EM \"DescarregarEventos() \" - \"onPostExecute()\"");
e.printStackTrace();
}
}
}
}
You can try to notify after data is added to adapter. So, at the end of onCreate function you can add the following line:
mAdapter.notifyDataSetChanged();