Putting a String ArrayList into SQLite Database - java

I am having trouble getting the entire string put into my arraylist correctly. I am assuming the error has something to do with my custom textwatcher or how I am looping through the array list. Here is my code:
case R.id.action_add:
Workout workout = new Workout("", "", "", "");
workoutList.add(workout);
ListView exerciseList = (ListView) findViewById(R.id.exerciseListView);
CustomAdapter myAdapter = new CustomAdapter(this, R.layout.custom_list, workoutList);
exerciseList.setAdapter(myAdapter);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public class CustomAdapter extends ArrayAdapter<Workout> {
private int layoutResource;
public CustomAdapter(Context context, int layoutResource, List<Workout> workoutList) {
super(context, layoutResource, workoutList);
this.layoutResource = layoutResource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
view = layoutInflater.inflate(layoutResource, null);
}
Workout workout = getItem(position);
if (workout != null) {
final EditText exercise = (EditText) view.findViewById(R.id.exercise);
final EditText reps = (EditText) view.findViewById(R.id.reps);
final EditText sets = (EditText) view.findViewById(R.id.sets);
if (exercise != null){
exercise.addTextChangedListener(new CustomWatcher(exercise));
}
if (reps != null) {
reps.addTextChangedListener(new CustomWatcher(reps));
}
if (sets != null) {
sets.addTextChangedListener(new CustomWatcher(sets));
}
}
return view;
}
}
//Textwatcher class
class CustomWatcher implements TextWatcher {
private View view;
public CustomWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
public void afterTextChanged(Editable editable) {
String text = editable.toString();
switch (view.getId()) {
//exercises
case R.id.exercise:
exercises.add(text);
break;
//reps
case R.id.reps:
reps.add(text);
break;
//sets
case R.id.sets:
sets.add(text);
break;
}
}
}
}
The cases are buttons. So when I click the add button I am trying to add my custom list view to my page which includes three text views. Then when I click save I am trying to get it to save the data from each edit text position into an array list to store into my data base.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection for menu
switch (item.getItemId()) {
case R.id.action_save:
String title = MyWorkoutsActivity.workouts.get(workoutID);
String ex;
String rp;
String st;
SQLDatabase db = new SQLDatabase(this);
for(int i = 0; i < workoutList.size(); i++){
//exercises, reps, and sets always same number so only one for loop needed
ex = exercises.get(i);
rp = reps.get(i);
st = sets.get(i);
db.addExercise(new Workout(title, ex, rp, st));
}
List<Workout> workouts = db.getAllExercises();
for (Workout wo : workouts) {
String log = "Workout " + wo.getWorkout() + "Exercise " + wo.getExercise() + " ,Reps " + wo.getReps() + " ,Sets " + wo.getSets();
// Writing workouts to log
Log.d("Workout ", log);
}
Intent intent = new Intent(this, MyWorkoutsActivity.class);
startActivity(intent);
return true;

This is happening because the listener method afterTextChanged is lunched after the first letter typed in so it will save the first letter into the list and so on
until you end up with a list of characters.
the solution is : simply don't use the textwatcher because you want to save the data when the user presses the save button so add the data to the exercises list when the button is hit like this code :
public void onClick(View view){
//the exercise and reps and sets are the EditText fields that you have
exercises.add(exercise.getText());
exercises.add(reps.getText());
exercises.add(sets.getText());
}

Related

Add urlImage 3 times to AdapterViewPager problem - AndroidX

I supposed to get ImageDisplay from ArrayJson, it will hit API 3 times
this function will send urlimage 3 times
for(i=0; i<3; i++){send(UrlImage);}
this works
private void getViewYoyo(){
String[] str = new String[3];
adapterViewPagerHot = new AdapterViewPagerHot(getActivity(), str);
str[0]="https://scx1.b-cdn.net/csz/news/800/2019/1-nasastessmis.jpg";
str[1]="https://i.chzbgr.com/full/8803531264/hD42E57C6/";
str[2]="https://scx1.b-cdn.net/csz/news/800/2019/1-nasastessmis.jpg";
viewPager.setAdapter(adapterViewPagerHot);
}
But this doesn't work
public void getHighlightMainActivity(int ReceivedDummyUrutan, int ReceivedTotalThread, int ReceivedDummyID, String ReceivedDummyTitle, String ReceivedDummyPublishTime, String ReceivedDummyImageOri, String ReceivedDummyShortDescription){
String[] str = new String[ReceivedTotalThread];
adapterViewPagerHot = new AdapterViewPagerHot(getActivity(), str);
if(ReceivedDummyUrutan==0)
str[0]=ReceivedDummyImageOri;
if(ReceivedDummyUrutan==1)
str[1]=ReceivedDummyImageOri;
if(ReceivedDummyUrutan==2)
str[2]=ReceivedDummyImageOri;
if(ReceivedDummyUrutan==ReceivedTotalThread-1) {
viewPager.setAdapter(adapterViewPagerHot);
}
}
This is adapterViewPager.java
public class AdapterViewPagerHot extends PagerAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
/*private Integer[] images = {R.drawable.cat_mermaid_cartoon_grumpy_cat_94004_1280x720,R.drawable.catnrobot,R.drawable.kleptocats,R.drawable.magiccat,R.drawable.flyingcat};*/
public String image_url[];
public AdapterViewPagerHot(Context context, String[] list) {
this.mContext = context;
this.image_url = list;
}
#Override
public int getCount() {
return image_url.length;
}
public void setUrls(String[] list){
this.image_url = list;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
public View vi;
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = layoutInflater.inflate(R.layout.item_viewpagerdisplay, null);
final Context sContext = mContext;
ImageView imageView = vi.findViewById(R.id.imageView);
final ImageView ICONHotViewPagerSaving = vi.findViewById(R.id.ICON_HotViewPagerSaving);
/*imageView.setImageResource(images[position]);*/
Glide.with(sContext).load(image_url[position]).into(imageView);
vi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(sContext, "Slide" + (position+1) + "Clicked", Toast.LENGTH_SHORT).show();
}
});
final Boolean[] boollatestnewssaving = {false};
ICONHotViewPagerSaving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boollatestnewssaving[0] == true){
Toast.makeText(v.getContext(), "Turn Off Saved News ", Toast.LENGTH_SHORT).show();
ICONHotViewPagerSaving.setImageResource(R.drawable.saved_off);
boollatestnewssaving[0] = false;
/*updateSavedNewsSaving("update_newssaving", id, false);*/
} else if(boollatestnewssaving[0] == false) {
Toast.makeText(v.getContext(), "Turn On Saved News ", Toast.LENGTH_SHORT).show();
ICONHotViewPagerSaving.setImageResource(R.drawable.saved_on);
boollatestnewssaving[0] = true;
/*updateSavedNewsSaving("update_newssaving", id, true);*/
}
}
});
ViewPager vp = (ViewPager) container;
vp.addView(vi, 0);
return vi;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
What will happen with GetHighlight function is it will show the third image only, the first and second image was blank
I am not sure how to make it works like this
String test[]=new String[]{urlImageSend>>Image1, urlImageSend>Image2, urlImageSend>>Image3}
by hitting using for 3 times
Declare one ArrayList which will hold the image URLs in your activity class like this
ArrayList<String> list = new ArrayList<>();
Now define one function which will insert the image URL's in the ArrayList
list.add(imageURL);
Now create your viewpager adapter and set the adapter
adapterViewPagerHot = new AdapterViewPagerHot(getActivity(), list);
Make sure you change string to arraylist in the AdapterViewPagerHot class

switch state is not stable in listview when scrolling

I'am new to android and i use sample for my listview. because of that i can't change the code. i have one switch button in each item of my Listview. when i scroll the Listview switches change state randomly. how can i make switch state stable?
my listview class adapter:
public class MyCustomCursorAdapter extends CursorAdapter {
LIGHTS calling_activity;
private DatabaseHelper dbHelper;
public MyCustomCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
this.calling_activity = (LIGHTS) context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
return view;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.adapter,parent,false);
}
#Override
public void bindView(final View view, Context context, Cursor cursor) {
((TextView)view.findViewById(R.id.id)).setText(cursor.getString(cursor.getColumnIndex(dbHelper._ID)));
((TextView)view.findViewById(R.id.KEYCODE)).setText(cursor.getString(cursor.getColumnIndex(dbHelper.TITLE)));
((TextView)view.findViewById(R.id.NAME)).setText(cursor.getString(cursor.getColumnIndex(dbHelper.DESC)));
ImageView option = view.findViewById(R.id.itemoption);
Switch thisswitch = view.findViewById(R.id.onoff);
thisswitch.setTag(cursor.getString(cursor.getColumnIndex(dbHelper._ID)));
thisswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { calling_activity.myOnCheckedChangedHandler((String)buttonView.getTag(),isChecked);
}
});
option.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView itemID = (TextView) view.findViewById(R.id.id);
TextView itemTitle = (TextView) view.findViewById(R.id.KEYCODE);
TextView itemDesc = (TextView) view.findViewById(R.id.NAME);
String myId = itemID.getText().toString();
String myTitle = itemTitle.getText().toString();
String myDesc = itemDesc.getText().toString();
Intent intent = new Intent(calling_activity, ModifyActivity.class);
intent.putExtra("Id", myId);
intent.putExtra("Title", myTitle);
intent.putExtra("Desc", myDesc);
calling_activity.startActivity(intent);
}
});
}
}
and in my Lights activity :
#Override
public void myOnCheckedChangedHandler(String id, boolean check_status) {
Toast.makeText(
this,
"You changed the status for the row with an id of " + id +
" the status is now " + new Boolean(check_status).toString(),
Toast.LENGTH_SHORT).show();
String name = cursor.getString(cursor.getColumnIndex(dbHelper.DESC));
if(new Boolean(check_status).toString().equals("true")){
Toast.makeText(this,name +" is ON", Toast.LENGTH_SHORT).show();
}
}
Please manage through if/else case inside bindView at adapter, You need to check the switch condition like below :
// set the code into bind
if(switchCondition1 == 1)
{
//set the code as per condition wise
}else{
//
}
After change the state you also need to change the state into your list item and use notifydatasetChanged() method to refresh the list items.

Android - Adding Views to Images doesn't update - onClick

Summary
When a user clicks on the RecyclerView item, I would like to add tags to that image from the information that has been stored in a BaaS [Sashido] (X Co-ordinates, Y Co-ordinates and Tag name). But, the problem I'm having isn't getting the position per-say. I create a toast when the image has been clicked, it shows the correct position corresponding to the view itself. (zero for the beginning, so on and so forth)
But how to update the position once the user clicks on another item in the list, so that the tags that correspond to the position in the array in Sashido, match the position in the RecyclerView, because at the moment the first row in the Sashido class is populating all images with that row's tags.
My assumption was to the pass the position to the getTagInformation() method using getLayoutPosition() so that when objects.get(position) array is called, it'll get the same position for Sashido class but it isn't. I feel the adapter must not be updating correctly after the user has clicked on a new item.
onBindViewHolder:
#Override
public void onBindViewHolder(RecyclerViewHolderPreviousPosts holder, int position) {
holder.bind(previousPostsList.get(position), listener);
}
onBind:
void bind(final PreviousPostsDataModel model, final OnItemClickListener listener) { ...
uploadedImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (count == 0) {
imageid = model.getImageId();
Toast.makeText(App.getContext(), "Image ID: " + imageid, Toast.LENGTH_SHORT).show();
Toast.makeText(App.getContext(), "Position: " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
getTagInformation(getLayoutPosition());
} else {
Log.e("qwert", "" + imageid);
imageContainer.removeAllViews();
imageContainer.addView(uploadedImage);
count = 0;
}
}
});
... }
getTagInformation:
private void getTagInformation(final int position) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("FashionFeed");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
Toast.makeText(context, "" + position, Toast.LENGTH_SHORT).show();
JSONArray tagNamesArray = objects.get(position).getJSONArray("tagName");
JSONArray posXArray = objects.get(position).getJSONArray("tagPointX");
JSONArray posYArray = objects.get(position).getJSONArray("tagPointY");
for (int i = 0; i < tagNamesArray.length(); i++) {
for (int t = 0; t < tagNamesArray.length(); t++) {
tagNames.add(tagNamesArray.optString(t));
tagXPositions.add(posXArray.optString(t));
tagYPositions.add(posYArray.optString(t));
}
for (int o = 0; o < tagNamesArray.length(); o++) {
tag = new TextView(App.getContext());
tag.setX(Float.parseFloat(tagXPositions.get(o)));
tag.setY(Float.parseFloat(tagYPositions.get(o)));
tag.setText(tagNames.get(o));
tag.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
tag.setMaxLines(1);
tag.setTextSize(11);
tag.setClickable(true);
tag.setHintTextColor(Color.WHITE);
tag.setTextColor(Color.WHITE);
tag.setBackgroundResource(R.drawable.tags_rounded_corners);
imageContainer.addView(tag);
count = 1;
}
}
} else {
Toast.makeText(context, "" + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
I have also tried
public void getTagInformation(String imageid) {
ParseQuery query = ParseQuery.getQuery("FashionFeed");
query.WhereEqualTo("objectId", imageId);
....
}
with the imageId passed into the method and with also me manually entering an objectId that will match, it'll still only produce the tags that belong to that objectId. it just doesn't seem that this query is going through all of the objects. Just getting the tag information from that one object and then setting all the images with those tags.
if you need me to provide anymore code, I'm more than happy to.
Hi #BIW please follow below link link
In onBindViewHolder, you are adding listener every time, so it returns same object every time as recyclerView ViewHolder pattern uses same object to render recyclerView item in onBindViewHolder. So you need to add when you are creating holder object and set listener to it so that you will get a proper position.
package com.subbu.moviemasti.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import com.subbu.moviemasti.Constants;
import com.subbu.moviemasti.R;
import com.subbu.moviemasti.entities.Movie;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Created by subrahmanyam on 25-11-2015.
*/
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder> {
private final List<Movie> movieList;
private onRecyclerViewItemClickListener mItemClickListener;
public MovieAdapter(List<Movie> movieList) {
this.movieList = movieList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.grid_item, null);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Movie movie = movieList.get(position);
String imageUrl = Constants.MOVIE_POSTER_BASE_URL + movie.getPosterPath();
if (imageUrl != null) {
Picasso.with(holder.posterImage.getContext()).load(imageUrl).
placeholder(R.drawable.img_default).
into(holder.posterImage);
}
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public int getItemCount() {
return movieList.size();
}
public void setOnItemClickListener(onRecyclerViewItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
public interface onRecyclerViewItemClickListener {
void onItemClickListener(View view, int position);
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
#Bind(R.id.poster)
ImageView posterImage;
public ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
mItemClickListener.onItemClickListener(v, getAdapterPosition());
}
}
}
Where we are creating adaper object, from there we need to set listener
like adapter.setOnItemClickListener(this)
class MyActivity extendsActivity implements onRecyclerViewItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
manager = new GridLayoutManager(getActivity(), cols);
gridView.setLayoutManager(manager);
gridView.setAdapter(adapter);
adapter.setOnItemClickListener(this);
}
#Override
public void onItemClickListener(View view, int position) {
//Do wantever you want to do
}
}
From ViewHolder class we need to pass position of a recyclerView or we can write code what you need to execute when click on item.
Solved the problem. It wasn't so much that the position was wrong, it was because I was trying to find the tags before I was populating the list of images due to Parse's FindInBackground() callback, it was being populated far too late.
The solution was that I got the JSONArray that contained the Tag names, x-coordindates and y co-ordinates inside the original query that was populating the original list of images. So they would execute simultaneously, then I passed the JSONArray values into the model, which then was passed to the bind() function in the Adapter.
Before, the problem was that the adapter was binding all of the tags onto every image, so when the click event happened on the image it would only add the tag to the imageContainer that was currently selected (in the current position), not any partiular view in any particular position.
This made it so every time the image was clicked it was always finding the first object in the database and assigning it to the selected image. [due to the click event triggering the getTagInformation() function).
With the automation of the getTagInformation method within the Bind function of the ViewHolder, I was able to populate every image with the correct tags and further manipulate it using an onClickListener assigned to the image as shown below:
RecyclerView Holder:
public class RecyclerViewHolderPreviousPosts extends RecyclerView.ViewHolder implements View.OnClickListener {
// View holder for gridview recycler view as we used in listview
public TextView createdAt;
public ImageView uploadedImage;
public TextView caption;
TextView number_of_likes;
TextView number_of_comments;
TextView number_of_tags;
public ImageView comments;
public RelativeLayout imageContainer;
RecyclerViewHolderPreviousPosts(View view) {
super(view);
// Find all views ids
this.createdAt = (TextView) view
.findViewById(R.id.created_date);
this.uploadedImage = (ImageView) view
.findViewById(R.id.image);
this.caption = (TextView) view
.findViewById(R.id.caption_post);
this.number_of_likes = (TextView) view
.findViewById(R.id.number_of_likes);
this.number_of_comments = (TextView) view
.findViewById(R.id.number_of_comments);
this.number_of_tags = (TextView) view
.findViewById(R.id.number_of_tags);
this.comments = (ImageView) view
.findViewById(R.id.comments_image);
this.imageContainer = (RelativeLayout) view
.findViewById(R.id.image_container);
view.setOnClickListener(this);
}
void bind(PreviousPostsDataModel model1, final int position) { ....
model = previousPostsList.get(position);
getTagInformation();
....}
private void getTagInformation() {
for (int o = 0; o < model.getTagSize(); o++) {
tag = new TextView(App.getContext());
tag.setX(Float.parseFloat(model.getXpoints(o)));
tag.setY(Float.parseFloat(model.getYpoints(o)));
Log.e("x", "" + tag.getX());
Log.e("y", "" + tag.getY());
tag.setText(model.getTagName(o));
tag.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
tag.setMaxLines(1);
tag.setTextSize(11);
tag.setClickable(true);
tag.setHintTextColor(Color.WHITE);
tag.setTextColor(Color.WHITE);
tag.setBackgroundResource(R.drawable.tags_rounded_corners);
imageContainer.addView(tag);
tags.add(tag);
}
}
#Override
public void onClick(View v) {
if (count == 0) {
for (int i = 0; i < tags.size(); i++) {
tags.get(i).setVisibility(View.INVISIBLE);
}
count = 1;
}
else {
for (int j = 0; j < tags.size(); j++) {
tags.get(j).setVisibility(View.VISIBLE);
}
count = 0;
}
}
}
Profile Fragment [Original Query] :
private void populateSelectedUserRecyclerView(String objectid) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("FashionFeed");
query.whereEqualTo("uploader", ParseObject.createWithoutData("_User", objectid));
query.orderByDescending("createdAt");
Log.e("get order", "ordered");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
Log.e("gets done", "gets into done");
if(e == null) {
if (objects.size() > 0) {
Log.e("does it get here", "it got here");
latestPostList = new ArrayList<>();
for (ParseObject j : objects) {
JSONArray tagNamesArray = j.getJSONArray("tagName");
JSONArray posXArray = j.getJSONArray("tagPointX");
JSONArray posYArray = j.getJSONArray("tagPointY");
latestPostList.add(new PreviousPostsDataModel(tagNamesArray, posXArray, posYArray));
}
}
else {
no_follow_display.setVisibility(View.VISIBLE);
no_follow_display.setText(R.string.no_posts);
no_follow_display.bringToFront();
recyclerView.setVisibility(View.GONE);
}
adapter = new RecyclerViewAdapterPreviousPosts(getActivity(), latestPostList, listener);
recyclerView.setAdapter(adapter);// set adapter on recyclerview
adapter.notifyDataSetChanged();
}
else {
Log.e("failed", "failed" + e.getMessage());
}
}
});
}
Thanks for your help.
If I understand correctly question the problem is that ParseQuery don't return objects in the same order. So the assumptions that position of object in Your RecycleView is the same as in ParseDatabase is wrong.
If u want to get TAG from Sashido You should firstly make some relations to Images e.g additional column. Then make query white extra parameter like:
private static final String UNIQ_TAG_ID= "tagId";
query.whereContainedIn(UNIQ_TAG_ID, id);
or get All ParseObjects like u doing now and find that TAG that correspond to Your image, then take info.

Delete checked item from list view and data from database, using adapter class

public class delete extends BaseAdapter {
SQLiteDatabase db;
String am;
private final Context c;
private final ArrayList<String> str;
private final String[] number;
ArrayList<Integer> checks=new ArrayList<Integer>();
public delete(Context c, ArrayList<String> str, String[] number, ArrayList<Integer> checks) {
this.c = c;
this.str = str;
this.number = number;
this.checks=checks;
}
#Override
public int getCount() {
return str.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater= (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View ListView ;
if(convertView==null)
{
ListView=new View(c);
ListView=inflater.inflate(R.layout.button,null);
TextView textview=(TextView) ListView.findViewById(R.id.textView6);
textview.setText(str.get(position));
}
else
{
ListView=(View)convertView;
}
Button btnupdate=(Button)ListView.findViewById(R.id.button4);
//checkbox declaration
CheckBox chk=(CheckBox)ListView.findViewById(R.id.chk1);
btnupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db=c.openOrCreateDatabase("Student",Context.MODE_PRIVATE, null);
String num = number[position];
Cursor cc=db.rawQuery("select mobile from detail where mobile='"+num+"'", null);
if (cc.moveToFirst()) {
do {
am = cc.getString(cc.getColumnIndex("mobile"));
} while (cc.moveToNext());
}
Intent i=new Intent(c,Update.class);
i.putExtra("value",am);
c.startActivity(i);
}
});
return ListView;
}
}
//It show all the data in list view with update button and check box in list view. There is delete button which is suppose to delete all the item which is checked.
//Delete button is on main activity where list view is added.
You can create a method in your DataBase class and pass the table name and entry to be deleted along with id if any.Call the method at onClick of ListView item.
public void deleteEntry(String tableName,String columnName,String id)
{
openDatabase();
database.delete(tableName, columnName + " = ?",new String[] { id });
closeDatabase();
}

Issues with a tagging system using Autocomplete android

I am trying to implement something similar to facebook's search system, where if a user starts typing in a name it brings autocomplete suggestions based on the letters typed, and with an additional option to search for more results. Each result is an object and not a string, and I have tried adding an extra result for search but every time I click on search or one of the objects a replace text occurs with the object as oppose to the name and I know it is a method of the autocomplete widget. Is there another way to go about it?
Here is my code:
private AutoCompleteTextView sx;
sx = (AutoCompleteTextView) findViewById(R.id.sx);
if(sadapter == null) {
sadapter = new Sadapter(PostActivity.this, usersFound);
sx.setAdapter(sadapter);
}
sx.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (sx.getText().toString().length() <= 3 && sadapter != null) {
usersFound.clear();
sadapter.notifyDataSetChanged();
}
if (sx.getText().toString().length() > 3) {
usersFound.clear();
sadapter.notifyDataSetChanged();
Log.d(Constants.DEBUG, "Changing text " + s);
sxname = s.toString();
testCreate();
sadapter.notifyDataSetChanged();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
sx.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DatabaseUser newAdd = usersFound.get(position);
if(position == searchServerIndex) {
sx.setText(sxname);
usersFound.clear();
sadapter.notifyDataSetChanged();
apiGetPossibleCandidates();
} else {
sx.setText("");
}
}
});
private void testCreate() {
DatabaseUser nuser1 = new DatabaseUser("userid", "pictureid", "Jon");
DatabaseUser nuser2 = new DatabaseUser("userid", "pictureid", "Jonny");
DatabaseUser nuser3 = new DatabaseUser("userid", "pictureid", "Jong");
DatabaseUser nuser4 = new DatabaseUser("userid", "pictureid", "Joan");
DatabaseUser searchServer = new DatabaseUser("SearchId", "pictureid", "Search " + sxname);
usersFound.add(nuser1);
usersFound.add(nuser2);
usersFound.add(nuser3);
usersFound.add(nuser4);
searchServerIndex = usersFound.size();
usersFound.add(searchServer);
if(sadapter != null) {
sadapter.notifyDataSetChanged();
}
}
This is the adapter:
public class Sadapter extends ArrayAdapter<DatabaseUser> {
private Context mContext;
private List<DatabaseUser> usersSearch;
private List<DatabaseUser> usersFiltered;
public Sadapter(Context context, List<DatabaseUser> usersAdded) {
super(context, 0, usersAdded);
mContext = context;
usersSearch = usersAdded;
}
#Override
public int getCount() {
return usersSearch.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.user_autosearch_item, null);
}
//helps for recycling
final ViewHolder holder = new ViewHolder();
holder.userTxt = (TextView) v.findViewById(R.id.userTxt);
v.setTag(holder);
String name = usersSearch.get(position).getName();
holder.userTxt.setText(name);
return v;
}
static class ViewHolder {
TextView userTxt;
}
}
you can override getItem() method in your adapater and return the object of DataBaseUser of particular position from the searchlist.. like
#Override public DatabaseUser getItem(int position) {
return usersSearch.get(position);
}
So from your onClick method you can call this method and it will give you DatabaseUser object from which you can retrive your text. I hope it helps you ..

Categories

Resources