populate listview from String array using Json parsing - java

I am trying to make a activity which has a listview ,it has edittexts,it displays the previously stored data and when clicked on edittexts and edit them, it stores the edited data and displays new data on list view. I am using hashmap to parse json values. Could you help me?
Here is my code:
public class AdditionalNutrientGoalsActivity extends ActionBarActivity
{
private static final String TAG = AdditionalNutrientGoalsActivity.class.getName();
HashMap<String, Integer> map = new HashMap<String, Integer>();
private String[] arrText =
new String[]{"Saturated Fat","Trans fat","polyunsaturated fat","Sodium","Fiber","Monosaturated Fat","Potassium"
,"Sugar","Iron","Cholestrol","Calcium","Vitamin C","Vitamin A"};
private String[] arrTemp =
new String[]{ "00 %","00 %","00 %","38 %","77 %","1049 %","00 %","00 %","38 %"
,"77 %","1049 %","77 %","1049 %"};// for now hardcodedvalues
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_additional_nutrient_goals);
MyListAdapter myListAdapter = new MyListAdapter();
ListView listView = (ListView) findViewById(R.id.customlist1);
listView.setAdapter(myListAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("list view", position + "");
showDialog(arrText[position]);
// Toast.makeText(getApplicationContext(),"Saved",Toast.LENGTH_SHORT).show();
}
});
ImageView IVback = (ImageView) findViewById(R.id.back);
IVback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AdditionalNutrientGoalsActivity.this.finish();
}
});
GetData getData=new GetData();
getData.execute();
}
void showDialog(String title)
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
AdditionalNutrientGoalsActivity.this);
// set title
alertDialogBuilder.setTitle(title);
alertDialogBuilder
.setMessage("Enter in gm/day")
.setCancelable(false)
.setPositiveButton("Set", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
//AdditionalNutrientGoalsActivity.this.finish();
}
})
.setView(new EditText(AdditionalNutrientGoalsActivity.this))
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
private class MyListAdapter extends BaseAdapter
{
#Override
public int getCount() {
if(arrText != null && arrText.length != 0){
return arrText.length;
}
return 0;
}
#Override
public Object getItem(int position) {
return arrText[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String data="";
//ViewHolder holder = null;
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = AdditionalNutrientGoalsActivity.this.getLayoutInflater();
convertView = inflater.inflate(R.layout.custom_additional_nutri, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.textView45);
holder.editText1 = (TextView) convertView.findViewById(R.id.textView46);
data =holder.editText1.getText().toString();
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.ref = position;
holder.textView1.setText(arrText[position]);
holder.editText1.setText(data);
holder.editText1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
// arrTemp[holder.ref] = arg0.toString();
saveData saveData=new saveData();
saveData.execute();
}
});
return convertView;
}
private class ViewHolder {
TextView textView1;
TextView editText1;
int ref;
}
}
and this is my GetData functionality:
private class GetData extends AsyncTask<String, Void, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
ArrayList<NameValuePair> parameters = new ArrayList<>();
parameters.add(new BasicNameValuePair("username", SharedPref.getData(getApplicationContext(), SharConstants.username)));
parameters.add(new BasicNameValuePair("password", SharedPref.getData(getApplicationContext(), SharConstants.password)));
// parameters.add(new BasicNameValuePair("token", SharedPref.getData(getApplicationContext(), SharConstants.token)));
parameters.add(new BasicNameValuePair("date_time", SharedPref.getData(getApplicationContext(), SharConstants.date_time)));
GetJsonFromServer getJsonFromServer = new GetJsonFromServer();
String response = getJsonFromServer.getJson(ApiList.getAdditionalNutrientGoals, "POST", parameters);
Log.e(TAG, response);
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try
{
JSONObject jsonObject = new JSONObject(s);
JSONObject response = jsonObject.getJSONObject("response");
if(response.getInt("success") == 1)
{
JSONObject object= response.getJSONObject("data");
ArrayList<HashMap<String,Integer>> parameters = new ArrayList<HashMap<String, Integer>>();
// adding each child node to HashMap key => value
map.put("id",object.getInt("id"));
map.put("user_id",object.getInt("user_id"));
map.put("saturated_fat",object.getInt("saturated_fat"));
map.put("polyunsaturated_fat",object.getInt("polyunsaturated_fat"));
map.put("monounsaturated_fat",object.getInt("monounsaturated_fat"));
map.put("trans_fat",object.getInt("trans_fat"));
map.put("cholesterol",object.getInt("cholesterol"));
map.put("sodium",object.getInt("sodium"));
map.put("potassium",object.getInt("potassium"));
map.put("fiber", object.getInt("fiber"));
map.put("sugar", object.getInt("sugar"));
map.put("Vitamin_A", object.getInt("Vitamin_A"));
map.put("Vitamin_C", object.getInt("Vitamin_C"));
map.put("calcium", object.getInt("calcium"));
map.put("iron", object.getInt("iron"));
parameters.add(map);
Log.d("map","map"+" "+parameters);
}
else
{
Toast.makeText(getApplicationContext(), "Server Error, Try Again Later.", Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e(TAG, e.toString());
Toast.makeText(getApplicationContext(), "Server Error", Toast.LENGTH_LONG).show();
}
}
I am not getting idea as to how to store data and fetch data.

Related

toogle listener associated with checkbox with adapter

Im building a simple aplication with a recycleView/CardLayout, i followeed this tutorial.
I see many questions answered for the card click, but what i need is to handle listeners with diferent actions when the user clicks the title or the user clicks on the image in each card.
My problem is, when the user clicks a radiobutton i need to get the radio on the listener so i can handle check and uncheck because i need to do pass that to a builder
This is what i have at the moment:
public class SimiliarPlantsAdapter extends RecyclerView.Adapter<SimiliarPlantsAdapter.PlantViewHolder>{
ArrayList<Plant> plants = new ArrayList<Plant>();
Context context;
public static class PlantViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView plantName;
CheckBox plantCheck;
ImageView plantPhoto;
PlantViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
plantName = (TextView)itemView.findViewById(R.id.plantName);
plantCheck = (CheckBox)itemView.findViewById(R.id.plantCheck);
plantPhoto = (ImageView)itemView.findViewById(R.id.plantPhoto);
}
}
#Override
public PlantViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.similiar_photo_row, viewGroup, false);
PlantViewHolder pvh = new PlantViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PlantViewHolder holder, int position) {
holder.plantName.setText(plants.get(position).getSpecie());
holder.plantCheck.setText("Are you sure this is the plant?");
Log.d("foto",String.valueOf(holder.plantName));
String urlFoto = "http://10.0.2.2:3000/images/" + holder.plantName.getText().toString() + "/Thumbnail.jpg";
Picasso.with(context)
.load(urlFoto)
.resize(250, 250)
.into(holder.plantPhoto);
}
#Override
public int getItemCount() {
return plants.size();
}
public SimiliarPlantsAdapter(ArrayList<Plant> plants,Context context) {
this.plants = plants;
this.context = context;
}
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
MY Activity
public class SimiliarPhotos extends AppCompatActivity implements IResult,SimiliarPlantsAdapter.OnItemClickListener {
RecyclerView rv;
LinearLayoutManager llm;
ArrayList<Plant> plants = new ArrayList<Plant>();
SimiliarPlantsAdapter adapter;
CheckBox checkBox;
VolleyService mVolleyService;
IResult mResultCallback = null;
final String GETREQUEST = "GETCALL";
//login url connection
final String URL = "http://10.0.2.2:3000/plants";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_similiar_photos);
rv = (RecyclerView)findViewById(R.id.rv);
llm = new LinearLayoutManager(this);
llm.setAutoMeasureEnabled(true);
rv.setLayoutManager(llm);
initializeAdapter();
initVolleyCallback();
mVolleyService = new VolleyService(mResultCallback,this);
mVolleyService.getDataVolley(GETREQUEST,URL);
}
#Override
public void notifySuccess(String requestType, JSONObject response) {
Log.d("resposta",response.toString());
}
#Override
public void notifySuccess(String requestType, JSONArray response) {
Log.d("resposta",response.toString());
}
#Override
public void notifyError(String requestType, VolleyError error) {
Log.d("resposta",error.toString());
}
void initVolleyCallback(){
mResultCallback = new IResult() {
#Override
public void notifySuccess(String requestType, JSONObject response) {
}
#Override
public void notifySuccess(String requestType, JSONArray response) {
Plant plant;
Log.d("ENTERED","ENTEREDHERE1");
// iterate over the JSONArray response
for (int i=0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i); // get the individual object from JSONArray
int id = Integer.parseInt(object.getString("id")); // get the unique identifier from the object
String specie = object.getString("specie"); // get the name of the specie from the object
String description = object.getString("description"); // get the description of the object
plant = new Plant(id,specie,description); // construct the object
Log.d("plant",String.valueOf(plant));
plants.add(plant); // add the object to the arraylist so it can be used on the cardLayout
} catch (JSONException e) {
Log.d("ENTERED",e.toString());
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
#Override
public void notifyError(String requestType, VolleyError error) {
Log.d("resposta",error.toString());
}
};
}
public void initializeAdapter(){
Log.d("plants",String.valueOf(plants.size()));
adapter = new SimiliarPlantsAdapter(plants,SimiliarPhotos.this,SimiliarPhotos.this);
rv.setAdapter(adapter);
}
#Override
public void onTitleClicked(int position, int id, View clickedview) {
}
#Override
public void onImageClicked(int position, View clickedview) {
}
#Override
public void onCheckClicked(int position, String specie, View clickedview) {
adapter.getItemId(position);
CreateDialog(specie);
}
public void CreateDialog(String specie){
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(SimiliarPhotos.this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(SimiliarPhotos.this);
}
builder.setTitle("Esta é a sua escolha?")
.setMessage("Confirma " + specie + " como a planta que fotografou?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//TODO associa nome da planta a fotografia na base de dados
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
The volley init is the request, not so important for the question, since i get the data correctly
You need to implement CompoundButton.OnCheckedChangeListener for CheckBox.
Your_CHECK_BOX.setOnCheckedChangeListener(checkedChangeListener);
CompoundButton.OnCheckedChangeListener checkedChangeListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(compoundButton == YOUR_CHECK_BOX) {
if(isChecked) {
// when check box is checked, call your action listener just like you did for title click/image click etc
} else {
// when check box is unchecked, call your action listener just like you did for title click/image click etc
}
}

Android studio, ArrayList not displaying items in list view correctly

I have a spinner that i select data from which goes into a arraylist that is used with a list view to display the contents. I know the values are going into the Arraylist but when it comes to the list view it does not work correctly.
What happens is the first item will load in fine, but when i add another item the previous one disappears, while the new one is displayed one position down from the previous one, this repeats for each one i added.
create itinerary code:
public class CreateItinerary extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
TextView txtDate;
private Spinner spinnerAttraction;
private Spinner spinnerTransport;
private boolean saved;
// array list for spinner adapter
private ArrayList<Category> categoriesList;
private ProgressDialog pDialog;
private List<String> lables = new ArrayList<String>();
private ArrayList<ItineraryAdapter>Entities;
private ArrayList<ItineraryAdapter>finalEntities;
private LayoutInflater myInflator;
private View myView;
private DBManager db;
private myAdapter adapter;
private int ID;
private String NAME;
private String LOCATION;
private String TIME;
static final int DIALOG_ID = 0;
int hour_x;
int min_x;
private ListView ls;
private TextView TextTime;
private String ItineraryName;
private String URL_ATTRACTIONS = "http://10.0.2.2/TravelApp/get_all_spinner.php";
private String URL_TRANSPORT = "http://10.0.2.2/TravelApp/get_all_transport_minor.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_itinerary);
txtDate = (TextView) findViewById(R.id.tvSelectDate);
saved = false;
ls = (ListView)findViewById(R.id.listCreateItinerary);
myInflator = getLayoutInflater();
myView = myInflator.inflate(R.layout.list_create_itinerary, null);
spinnerAttraction = (Spinner) findViewById(R.id.spinnerAttraction);
spinnerTransport = (Spinner) findViewById(R.id.spinnerTransport);
db = new DBManager(this);
categoriesList = new ArrayList<Category>();
Entities = new ArrayList<ItineraryAdapter>();
finalEntities = new ArrayList<ItineraryAdapter>();
// spinner item select listener
spinnerAttraction.setOnItemSelectedListener(this);
spinnerTransport.setOnItemSelectedListener(this);
new GetAttractions().execute();
showTimePickerDialog();
Bundle bundle = getIntent().getExtras();
ItineraryName = bundle.getString("Itinerary Name");
(this).registerForContextMenu(ls);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if(v.getId()== R.id.listCreateItinerary){
this.getMenuInflater().inflate(R.menu.context_menu,menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.menuDelete:
return true;
default:
return super.onContextItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_button, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (saved == false) {
if (id == R.id.go_home) {
final TextView alertMessage = new TextView(this);
alertMessage.setText(" All changes will be lost are you sure you want to return back to the home page? ");
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Unsaved changes")
.setView(alertMessage)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(), QavelNav.class);
startActivity(i);
}
})
.setNegativeButton("No", null)
.create();
dialog.show();
}
}
else if(saved == true){
if (id == R.id.go_home) {
Intent i = new Intent(getApplicationContext(), QavelNav.class);
startActivity(i);
}
}
return super.onOptionsItemSelected(item);
}
public void pickDate(View v) {
DatePickerClass datepicker = new DatePickerClass();
datepicker.setText(v);
datepicker.show(getSupportFragmentManager(), "datepicker");
System.out.println(getDate());
}
public String getDate() {
String date;
date = txtDate.getText().toString();
return date;
}
public void addAttractionToItinerary(View v){
Entities.add(new ItineraryAdapter(ID,NAME,LOCATION,null));
loadAttractions();
System.out.println(ItineraryName);
}
public void addTransportToItinerary(View v){
Entities.add(new ItineraryAdapter(ID,NAME,LOCATION,null));
loadAttractions();
System.out.println(ItineraryName);
}
public void loadAttractions(){
adapter = new myAdapter(Entities);
ListView ls = (ListView) findViewById(R.id.listCreateItinerary);
ls.setAdapter(adapter);
for(int i =0; i < finalEntities.size(); i++){
System.out.println(finalEntities.get(i).NAME + " " + finalEntities.get(i).LOCATION + " " + finalEntities.get(i).TIME);
}
}
public void onSave(View v){
ContentValues values = new ContentValues();
for(int i = 0; i <finalEntities.size();i++) {
values.put(DBManager.ColItineraryName,ItineraryName);
values.put(DBManager.ColDate,txtDate.getText().toString());
values.put(DBManager.ColName,finalEntities.get(i).NAME );
values.put(DBManager.ColLocation,finalEntities.get(i).LOCATION);
values.put(DBManager.ColTime,finalEntities.get(i).TIME);
long id = db.Insert("Itinerary",values);
if (id > 0)
Toast.makeText(getApplicationContext(),"Added to Itinerary", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(),"cannot insert", Toast.LENGTH_LONG).show();
}
saved = true;
}
public void showTimePickerDialog(){
TextTime = (TextView) myView.findViewById(R.id.tvCreateItineraryTime);
TextTime.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
showDialog(DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id){
if(id== DIALOG_ID)
return new TimePickerDialog(CreateItinerary.this,KTimePickerListner, hour_x, min_x,false);
return null;
}
protected TimePickerDialog.OnTimeSetListener KTimePickerListner = new TimePickerDialog.OnTimeSetListener(){
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
hour_x = hourOfDay;
min_x = minute;
Toast.makeText(CreateItinerary.this,hour_x+" : " + min_x, Toast.LENGTH_LONG).show();
setTime(hour_x, min_x);
TIME = hour_x + ":" + min_x;
finalEntities.add(new ItineraryAdapter(ID,NAME,LOCATION,TIME));
}
};
public void setTime(int hour, int min){
TextTime.setText(hour_x+":"+min_x);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
NAME = categoriesList.get(position).getName();
LOCATION = categoriesList.get(position).getLocation();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
/**
* Adding spinner data
* */
private void populateSpinner() {
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName() + " - " + categoriesList.get(i).getLocation());
System.out.println(categoriesList.get(i));
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerAttraction.setAdapter(spinnerAdapter);
spinnerTransport.setAdapter(spinnerAdapter);
}
/**
* Async task to get all attraction categories
* */
private class GetAttractions extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching attraction categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_ATTRACTIONS, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("attraction");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
// new GetTransport().execute();
}
}
private class GetTransport extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching transport categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_TRANSPORT, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("transport");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
class myAdapter extends BaseAdapter {
public ArrayList<ItineraryAdapter> listItem;
ItineraryAdapter ac;
public myAdapter(ArrayList<ItineraryAdapter> listItem) {
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
ac = listItem.get(position);
TextView Name = (TextView) myView.findViewById(R.id.tvCreateItineraryName);
Name.setText(ac.NAME);
TextView Location = (TextView) myView.findViewById(R.id.tvCreateItineraryLocation);
Location.setText(ac.LOCATION);
return myView;
}
public void deleteItineraryItem(){
Entities.remove(ID);
finalEntities.remove(ID);
loadAttractions();
}
}
}
The public void loadAttractions(){..., is the medthod code that updates the list view, the 2 methods above it relate to separate buttons and add the spinner item to the array list (Entities), thank you to anyone who can help me.
instead of:
#Override
public Object getItem(int position) {
return null;
}
try this code:
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listItem.get(position); //return list item
}

OnItemClicklistener on list adapter that populate its items from database

I have a list view that implement swipelistadapter and app controller. The list view display correctly from the database, the only thing I need is to get position of each item and assign intent activity on each. These are my codes
public class SwipeListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieList;
private String[] bgColors;
public SwipeListAdapter(Activity tab1, List<Movie> movieList) {
this.activity = tab1;
this.movieList = movieList;
bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public Object getItem(int location) {
return movieList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_rows, null);
TextView serial = (TextView) convertView.findViewById(R.id.serial);
TextView title = (TextView) convertView.findViewById(R.id.title);
serial.setText(String.valueOf(movieList.get(position).id));
title.setText(movieList.get(position).title);
String color = bgColors[position % bgColors.length];
serial.setBackgroundColor(Color.parseColor(color));
return convertView;
}
}
Below Class is the main activity
public class Tab1 extends Fragment implements ViewSwitcher.ViewFactory, SwipeRefreshLayout.OnRefreshListener {
private int index;
private int[] images = new int[] { R.drawable.gallery1, R.drawable.gallery2, R.drawable.gallery3, R.drawable.gallery4, R.drawable.gallery5, R.drawable.gallery6, R.drawable.gallery7, R.drawable.gallery8 };
ImageSwitcher switcher;
android.os.Handler Handler = new Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private SwipeListAdapter adapter;
private List<Movie> movieList;
private ListView listView;
// private static final String url = "http://api.androidhive.info/json/movies.json";
private String URL_TOP_250 = "http://192.158.33.172/locator/test/refractor.php?offset=";
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
private static final String TAG = Tab1.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_1,container,false);
listView = (ListView) v.findViewById(R.id.list);
// Adding request to request queue
//Editted AppController.getInstance().addToRequestQueue(movieReq);
swipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_refresh_layout);
movieList = new ArrayList<>();
adapter = new SwipeListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
}
);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//String selectedFromList = (listView.getItemAtPosition(position).getString());
// String text = movieList[position];
Intent i = new Intent(getActivity(), Tab2.class);
// i.putExtra("TEXT", text);
startActivity(i);
}
});
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
switcher = (ImageSwitcher) getActivity().findViewById(R.id.imageSwitcher1);
switcher.setFactory(this);
switcher.setImageResource(images[index]);
switcher.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
index++;
if (index >= images.length) {
index = 0;
}
switcher.setImageResource(images[index]);
}
});
switcher.setInAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
switcher.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));
//auto change image
Handler.post(UpdateImage);
}
#Override
public void onRefresh() {
fetchMovies();
}
private void fetchMovies() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL_TOP_250 + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("postTitle");
Movie m = new Movie(rank, title);
movieList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
Runnable UpdateImage = new Runnable() {
public void run() {
// Increment index
index++;
if (index > (images.length - 1)) {
index = 0;
}
switcher.setImageResource(images[index]);
// Set the execution after 5 seconds
Handler.postDelayed(this, (3 * 1000));
}
};
#Override
public View makeView() {
ImageView myView = new ImageView(getActivity());
myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
myView.setLayoutParams(new ImageSwitcher.LayoutParams(Gallery.LayoutParams.
FILL_PARENT, Gallery.LayoutParams.FILL_PARENT));
return myView;
}
}
Any help will be appreciated. Thanks.
Code for getting a single item:
String singleItem = getItem(position);
this is quite straight forward. here is a modification to your onItemClickListener:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String text = movieList.get(position);
Intent i = new Intent(getActivity(), Tab2.class);
i.putExtra("TEXT", text);
startActivity(i);
}
});
just note that movieList object should be the same object you pass to your adapter

I can't add search feature to my listview

I have an listview in my application and when I add search to my listview it dosen't work at all.
when I add those code to my project, getfilter doesn't resolve.
enter code here
public class MyActivity extends Activity {
InputStream in;
BufferedReader reader;
String line = "1";
public ListView listView;
VehicleAdapter adapter;
ArrayList<String> dataItems = new ArrayList<String>();
public int star = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
G.currentActivity = this;
setContentView(R.layout.main);
// Adad.setTestMode(true);
ReadText();
// String[] dataArray = dataItems.toArray(new String[0]);
//String[] dataArray = getResources().getStringArray(R.array.listdata);
//List<String> dataTemp = Arrays.asList(dataArray);
// dataItems.addAll(dataTemp);
listView = (ListView) findViewById(R.id.mainList);
EditText ed = (EditText) findViewById(R.id.editText1);
ArrayList<Bitmap> arr_bitmaps = new ArrayList<Bitmap>(4);
adapter = new VehicleAdapter(MyActivity.this, arr_bitmaps, dataItems);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
ed.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// vaghti kar bar harfi vared kard josteju mikone :
MyActivity.this.adapter.getFilter().filter(arg0);
}
});
}
public class VehicleAdapter extends BaseAdapter {
ArrayList<String> arr_calllog_name = new ArrayList<String>();
public Activity context;
ArrayList<Bitmap> imageId;
public LayoutInflater inflater;
public VehicleAdapter(Activity context, ArrayList<Bitmap> arr_bitmaps, ArrayList<String> arr_calllog_name) {
super();
this.imageId = arr_bitmaps;
this.context = context;
this.arr_calllog_name = arr_calllog_name;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arr_calllog_name.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public class ViewHolder {
TextView txtName;
ImageButton btn;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.child_listview, null);
holder.txtName = (TextView) convertView.findViewById(R.id.childTextView);
holder.btn = (ImageButton) convertView.findViewById(R.id.childButton);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtName.setText(PersianReshape.reshape(arr_calllog_name.get(position)));
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/B Morvarid_YasDL.com.ttf");
//holder.txtName.setTypeface(G.defaultFont);
holder.txtName.setTypeface(custom_font);
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = arr_calllog_name.get(position);
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
return convertView;
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == R.id.contact) {
Intent intent = new Intent(MyActivity.this, ContactUs.class);
startActivity(intent);
}
return super.onOptionsItemSelected(menuItem);
}
private void ReadText() {
try {
in = this.getAssets().open("text.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
dataItems.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
my broblem is this code.
enter code here
MyActivity.this.adapter.getFilter().filter(arg0);
why getFilter() doesn't resolve?
Is it releted to my adaptor?
please help
why getFilter() doesn't resolve?
Because Filterable interface is not implemented in VehicleAdapter class.
To call adapter.getFilter().filter for Activity usng Adapter object need to implement Filterable interface in Adapter class and override getFilter.
See following example how to make Adapter Filterable:
Android Filter Custom ListView (BaseAdapter)
In custom adapter it would not work. this code for search will work in SimpleAdapter. For your adapter you have to write custom code for search.
Follow this link it would do as per your need (search filter in custom adapetr)
Custom Listview Adapter with filter Android

Cannot repopulate a listview with new JSON data - Java / Android

I have a listView populated with JSON data obtained from YouTube:
private VideosListView listView;
As of now - the listView succesfully populates with the data I'm looking for however I need to be able to repopulate it with updated data. Currently - I execute/populate the initial listView using:
new GetYouTubeUserVideosTask(responseHandler, playlist).execute();
What I'd like to do is repopulate it using a different value for String playlist:
String playlist = "TheMozARTGROUP‎";
new GetYouTubeUserVideosTask(responseHandler, playlist)
.execute();
View vg = findViewById(R.layout.home);
vg.invalidate();
P.S.
What I've attempted to use thus far does not seem to be working - nothing happens when I swipe the ViewPager - however if I set a toast there it will appear when swiping it.
I don't know why this has been such a difficult issue to nail down - but I'd be more than happy to leave a tip via paypal for anyone who can solve this issue.
http://i.stack.imgur.com/e0QqU.png
JAVA: Home.java
public class Home extends YouTubeBaseActivity implements
VideoClickListener {
private VideosListView listView;
private int mCurrentTabPosition = NO_CURRENT_POSITION;
private static final int NO_CURRENT_POSITION = -1;
private ListView drawerListView;
String playlist = "knocksteadyTV";
Activity activity;
int imageArray[];
String[] stringArray;
String runPrevious = "No";
private OnPageChangeListener mPageChangeListener;
ImagePagerAdapter adapter = new ImagePagerAdapter();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
final ViewPager mPager = (ViewPager) findViewById(R.id.view_pager);
adapter.notifyDataSetChanged();
mPager.setAdapter(adapter);
mPager.setOnPageChangeListener(mPageChangeListener);
listView = (VideosListView) findViewById(R.id.videosListView);
listView.setOnVideoClickListener(this);
new GetYouTubeUserVideosTask(responseHandler, playlist).execute();
mPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
Toast.makeText(getApplicationContext(), "onPageSelected",
Toast.LENGTH_SHORT).show();
String playlist = "TheMozARTGROUP‎";
new GetYouTubeUserVideosTask(responseHandler, playlist).execute();
adapter.notifyDataSetChanged();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(), "onPageScrolled",
// Toast.LENGTH_SHORT).show();
}
#Override
public void onPageScrollStateChanged(int pos) {
Toast.makeText(getApplicationContext(),
"onPageScrollStateChanged", Toast.LENGTH_SHORT).show();
String playlist = "TheMozARTGROUP‎";
new GetYouTubeUserVideosTask(responseHandler, playlist)
.execute();
adapter.notifyDataSetChanged();
}
});
mPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
onTabChanged(mPager.getAdapter(), mCurrentTabPosition, position);
position = mCurrentTabPosition;
int oldPos = mPager.getCurrentItem();
if (position > oldPos) {
System.out.print(position);
// Moving to the right
String playlist = "TheMozARTGROUP‎";
new GetYouTubeUserVideosTask(responseHandler, playlist)
.execute();
View vg = findViewById(R.layout.home);
vg.invalidate();
} else if (position < oldPos) {
// Moving to the Left
System.out.print(position);
String playlist = "TheMozARTGROUP‎";
new GetYouTubeUserVideosTask(responseHandler, playlist)
.execute();
View vg = findViewById(R.layout.home);
vg.invalidate();
}
mPager.setOnPageChangeListener(mPageChangeListener);
}
private void onTabChanged(PagerAdapter adapter,
int mCurrentTabPosition, int position) {
// TODO Auto-generated method stub
}
};}
private class MyActivityGetYouTubeUserVideosTask extends GetYouTubeUserVideosTask {
public MyActivityGetYouTubeUserVideosTask(Handler replyTo,
String username) {
super(replyTo, username);
// TODO Auto-generated constructor stub
}
#Override
protected void onPostExecute(Void result) {
if (result != null) {
// TODO update your list data
// note: assuming your data is stored in an ArrayList<MyData>,
// you cannot create a new one. you must clear() the current
// ArrayList and add() the result to it.
}
adapter.notifyDataSetChanged();
}
}
private void _initMenu() {
}
Handler replyTo = new Handler() {
#Override
public void handleMessage(Message msg) {
populateListWithVideos(msg);
};
};
Handler responseHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
populateListWithVideos(msg);
};
};
private void populateListWithVideos(Message msg) {
Library lib = (Library) msg.getData().get(
GetYouTubeUserVideosTask.LIBRARY);
listView.setVideos(lib.getVideos());
}
#Override
protected void onStop() {
responseHandler = null;
super.onStop();
}
#Override
public void onVideoClicked(Video video) {
Intent intent = new Intent(this, Player.class);
intent.putExtra("id", video.getId());
intent.putExtra("title", video.getTitle());
intent.putExtra("uploader", video.getUploader());
intent.putExtra("viewCount", video.getviewCount());
startActivity(intent);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ImagePagerAdapter extends PagerAdapter {
public ImagePagerAdapter(Activity act, int[] mImages,
String[] stringArra) {
imageArray = mImages;
activity = act;
stringArray = stringArra;
}
// this is your constructor
public ImagePagerAdapter() {
super();
}
private int[] mImages = new int[] { R.drawable.selstation_up_btn,
R.drawable.classical_up_btn, R.drawable.country_up_btn,
R.drawable.dance_up_btn, R.drawable.hiphop_up_btn,
R.drawable.island_up_btn, R.drawable.latin_up_btn,
R.drawable.pop_up_btn, R.drawable.samba_up_btn };
private String[] stringArray = new String[] { "vevo",
"TheMozARTGROUP‎", "TimMcGrawVEVO‎", "TiestoVEVO‎",
"EminemVEVO‎" };
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = Home.this;
ImageView imageView = new ImageView(context);
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view,
int position, long id) {
drawerListView.setItemChecked(position, true);
setTitle("......");
String text = "menu click... should be implemented";
Toast.makeText(Home.this, text, Toast.LENGTH_LONG).show();
drawerLayout.closeDrawer(drawerListView);
}
}
}
}
JAVA: GetYoutubeVideosTask.java
public class GetYouTubeUserVideosTask extends AsyncTask<Void, Void, Void> {
public static final String LIBRARY = "Library";
private final Handler replyTo;
private final String username;
public GetYouTubeUserVideosTask(Handler replyTo, String username) {
this.replyTo = replyTo;
this.username = username;
}
/*
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Void doInBackground(Void... arg0) {
try {
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet("https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc");
HttpResponse response = client.execute(request);
String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");
List<Video> videos = new ArrayList<Video>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String title = jsonObject.getString("title");
String id = jsonObject.getString("id");
String viewCount = jsonObject.getString("viewCount");
String uploader = jsonObject.getString("uploader");
String url;
try {
url = jsonObject.getJSONObject("player").getString("mobile");
} catch (JSONException ignore) {
url = jsonObject.getJSONObject("player").getString("default");
}
String thumbUrl = jsonObject.getJSONObject("thumbnail").getString("hqDefault");
videos.add(new Video(title, id, viewCount, uploader, url, thumbUrl));
}
Library lib = new Library(username, videos);
Bundle data = new Bundle();
data.putSerializable(LIBRARY, lib);
Message msg = Message.obtain();
msg.setData(data);
replyTo.sendMessage(msg);
} catch (ClientProtocolException e) {
Log.e("Feck", e);
} catch (IOException e) {
Log.e("Feck", e);
} catch (JSONException e) {
Log.e("Feck", e);
}
return null;
}
/*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Void result) {
//adapter.notifyDataSetChanged();
}
}

Categories