OrmLite get value from listView with Adapter - java

When I want to get a name of list which I pressed, I get "com.example.oleksandr.dream.DB.DreamDetails#528f8a90". How can I get a String value from my list? The problem is in "the onItemClick" methode.
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private DBHelper mDbHelper = null;
private DreamDetails dreamDetails;
private ListView mListView;
private DrawerLayout drawerLayout;
private Toolbar mToolbar;
private Dao<DreamDetails, Integer> dreamDetailsDao;
private List<DreamDetails> dreamList;
private int selectedRecordPosition = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listViewAllDreams);
try {
//Getting all Data from DB
dreamDetailsDao = getHelper().getDreamDetailsesDao();
dreamList = dreamDetailsDao.queryForAll();
// Set the header of the ListView
final LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.list_view, mListView, false);
mListView.addHeaderView(view);
// my own adapter!
mListView.setAdapter(new AdapterArrayDream(this,R.layout.list_view,dreamList,dreamDetailsDao));
mListView.setOnItemClickListener(this);
} catch (SQLException e) {
e.printStackTrace();
}
initToolbar();
initNavigationView();
FloatingActionButton myFab = (FloatingActionButton)findViewById(R.id.fab);
myFab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, NewDream.class);
startActivity(intent);
}
});
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(i > 0)
{
selectedRecordPosition = i - 1;
// final Intent intent = new Intent(this, ViewDream.class);
Log.i("TAAAAAAG", "onClick " + adapterView.getItemAtPosition(selectedRecordPosition));
// intent.putExtra("D", String.valueOf(adapterView.getItemAtPosition(selectedRecordPosition)));
// startActivity(intent);
}
}
private void initNavigationView() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawlerLayout);
}
private void initToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setTitle(R.string.app_name);
mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
});
// mToolbar.inflateMenu(R.menu.menu);
}
// This is how, DatabaseHelper can be initialized for future use
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_list_dreams, menu);
return true;
}
private DBHelper getHelper() {
if (mDbHelper == null) {
mDbHelper = OpenHelperManager.getHelper(this, DBHelper.class);
}
return mDbHelper;
}
}

To create a query which looks up an account by name and password you would do the following:
QueryBuilder<Account, String> qb = accountDao.queryBuilder();
Where where = qb.where();
// the name field must be equal to "foo"
where.eq(Account.NAME_FIELD_NAME, "foo");
// and
where.and();
// the password field must be equal to "_secret"
where.eq(Account.PASSWORD_FIELD_NAME, "_secret");
PreparedQuery<Account, String> preparedQuery = qb.prepareQuery();

Related

FirebaseRecyclerAdapter OnItemClick from fragment to fragment

I'm using the firebaseRecyclerAdaper on a fragment and i want to open an item from de populated list from firebase and send the data to a new fragment. Can u guys tell me please how can i start the FragmentDetail from the onCLickListener on FragmentAllPosts and pass the PostModel parameter to it?
Main Activity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "TAG" ;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference , postsRef;
private StorageReference profileImgRef;
private CircleImageView circleImageViewMain;
private TextView nameEdtTxt, emailEdtTxt;
Fragment fragment= null;
private RecyclerView recyclerView;
private FloatingActionButton fab;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
progressDialog= new ProgressDialog(this);
progressDialog.setMessage("Please wait!");
progressDialog.setCanceledOnTouchOutside(false);
//Initialize Firebase modules
firebaseAuth=FirebaseAuth.getInstance();
databaseReference= FirebaseDatabase.getInstance().getReference().child("users");
postsRef= FirebaseDatabase.getInstance().getReference().child("posts");
profileImgRef= FirebaseStorage.getInstance().getReference();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
circleImageViewMain = (CircleImageView) header.findViewById(R.id.circleImageHeader);
nameEdtTxt = (TextView) header.findViewById(R.id.txtName);
emailEdtTxt =(TextView)header.findViewById(R.id.txtEmail);
if (firebaseAuth.getCurrentUser()!=null){
LoadUserData(CheckUserDataBase());
}
ViewPager vp_pages= (ViewPager) findViewById(R.id.vp_pages);
PagerAdapter pagerAdapter=new FragmentAdapter(getSupportFragmentManager());
vp_pages.setAdapter(pagerAdapter);
TabLayout tbl_pages= (TabLayout) findViewById(R.id.tabs);
tbl_pages.setupWithViewPager(vp_pages);
tbl_pages.setTabTextColors(ColorStateList.valueOf(Color.parseColor("#FFFFFF")));
tbl_pages.setHorizontalScrollBarEnabled(true);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fragment= new AddPostFrag();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction= fragmentManager.beginTransaction();
transaction.add(R.id.add_post_container, fragment).commit();
fab.hide();
}
});
}
class FragmentAdapter extends FragmentPagerAdapter {
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new FragmentAllPosts();
case 1:
return new FragmentLosts();
case 2:
return new FragmentFounds();
}
return null;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
//
//Your tab titles
//
case 0:return "All";
case 1:return "Losts";
case 2: return "Founds";
default:return null;
}
}
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser user= firebaseAuth.getCurrentUser();
if (user == null){
SendUserToLogin();
} else {
CheckUserDataBase();
}
}
public static class PostsViewHolder extends RecyclerView.ViewHolder {
CircleImageView circleImageView;
ImageView imageView;
TextView authorNdate, location, description;
public PostsViewHolder(#NonNull View itemView) {
super(itemView);
circleImageView= itemView.findViewById(R.id.circleImageView_cv);
imageView= itemView.findViewById(R.id.imageView_cv);
authorNdate= itemView.findViewById(R.id.author_date_cv);
location = itemView.findViewById(R.id.location_cv);
description = itemView.findViewById(R.id.description_cv);
}
}
private void UpdateHome() {
}
private void LoadUserData(final String uid) {
try {
final File localFile =File.createTempFile("profile","png");
StorageReference filepath=profileImgRef.child(uid).child("profileImg/profile.png");
filepath.getFile(localFile)
.addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Picasso.get()
.load(localFile)
.placeholder(R.drawable.ic_account)
.into(circleImageViewMain);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this,
"Profile photo not found, please update your profile!",
Toast.LENGTH_SHORT).show();
SendUserToSetup();
}
});
} catch (IOException e) {
e.printStackTrace();
}
databaseReference.child(uid).child("userInfo").addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("name")){
String name = dataSnapshot.child("name").getValue().toString();
nameEdtTxt.setText(name);
String email = dataSnapshot.child("email").getValue().toString();
emailEdtTxt.setText(email);
} else {
Toast.makeText(MainActivity.this,
"Profile name does not exists, please update your profile",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);
}
#Override
protected void onStop() {
super.onStop();
}
private String CheckUserDataBase() {
final String userID =firebaseAuth.getCurrentUser().getUid();
databaseReference.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.child(userID).hasChild("userInfo")){
SendUserToSetup();
} else {
UpdateHome();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);
return userID;
}
private void SendUserToSetup() {
Intent i = new Intent(this,SetupActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
private void SendUserToLogin() {
Intent i = new Intent(this,LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (getSupportFragmentManager().getBackStackEntryCount() >0)
{
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
} else
{
super.onBackPressed();
}
fab.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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 (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id){
case R.id.nav_home:
super.onResume();
if (fragment!=null){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction= fragmentManager.beginTransaction();
transaction.remove(fragment).commit();
fab.show();
}
break;
case R.id.nav_profile:
super.onPause();
break;
case R.id.nav_my_posts:
super.onPause();
break;
case R.id.nav_messeges:
super.onPause();
break;
case R.id.nav_settings:
super.onPause();
break;
case R.id.nav_logout:
SendUserToLogin();
firebaseAuth.signOut();
break;
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Fragment with the FirebaseRecyclerAdapter
public class FragmentAllPosts extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private DatabaseReference postsRef;
private Context context= getContext();
Fragment mFragment;
Bundle mBundle;
public FragmentAllPosts() {
// Required empty public constructor
}
public static FragmentAllPosts newInstance(String param1, String param2) {
FragmentAllPosts fragment = new FragmentAllPosts();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
private RecyclerView recyclerAllPosts;
private ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
progressDialog= new ProgressDialog(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_all_posts,container,false);
postsRef= FirebaseDatabase.getInstance().getReference().child("posts");
recyclerAllPosts= v.findViewById(R.id.recycler_all_posts);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerAllPosts.setLayoutManager(linearLayoutManager);
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context=context;
}
#Override
public void onStart() {
super.onStart();
progressDialog.show();
FirebaseRecyclerOptions<PostsModel> options=
new FirebaseRecyclerOptions.Builder<PostsModel>()
.setQuery(postsRef,PostsModel.class)
.setLifecycleOwner(this)
.build();
FirebaseRecyclerAdapter<PostsModel,PostsViewHolder> adapter=
new FirebaseRecyclerAdapter<PostsModel, PostsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final PostsViewHolder holder, int position, #NonNull final PostsModel model) {
String processedTime= CalculateTime(model.getData());
Picasso.get().load(Uri.parse(model.getUserImg())).into(holder.circleImageView);
Picasso.get().load(Uri.parse(model.getImageUri())).into(holder.imageView);
holder.authorNdate.setText(model.getAuthor()+" updated "+processedTime);
holder.location.setText(model.getLocation());
holder.description.setText(model.getDescription());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment frag= new FragmentDetail();
getFragmentManager().beginTransaction().replace(R.id.add_post_container,frag)
.addToBackStack(null).commit();
}
});
}
#NonNull
#Override
public PostsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view= LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.card_view,viewGroup,false );
PostsViewHolder viewHolder= new PostsViewHolder(view);
return viewHolder;
}
};
recyclerAllPosts.setAdapter(adapter);
progressDialog.dismiss();
adapter.startListening();
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public String CalculateTime(String inputTime){
String timeOut;
Calendar currentTime= Calendar.getInstance();
SimpleDateFormat dateFormat= new SimpleDateFormat(getString(R.string.date_format));
dateFormat.format(currentTime.getTime());
SimpleDateFormat postFormat= new SimpleDateFormat(getString(R.string.date_format));
Calendar postTime = Calendar.getInstance();
try {
Date datePost=postFormat.parse(inputTime);
postTime.setTime(datePost);
} catch (ParseException e) {
e.printStackTrace();
}
long timeCurrent= currentTime.getTimeInMillis();
long timePost = postTime.getTimeInMillis();
long diff= timeCurrent- timePost;
long minutes= diff/(60*1000);
long hours = diff/(60 * 60 * 1000);
long days = diff/(24 * 60 * 60 * 1000);
if (minutes<59 && minutes>1){
timeOut=Long.toString(minutes)+" mins ago";
} else if (minutes<1){
timeOut=" just now";
}else if (hours<24 && minutes>59){
timeOut=Long.toString(hours)+" hour(s) ago";
}else {
timeOut=Long.toString(days)+" day(s) ago";
}
return timeOut;
}
static class PostsViewHolder extends RecyclerView.ViewHolder {
CircleImageView circleImageView;
ImageView imageView;
TextView authorNdate, location, description;
public PostsViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setTag(this);
circleImageView= itemView.findViewById(R.id.circleImageView_cv);
imageView= itemView.findViewById(R.id.imageView_cv);
authorNdate= itemView.findViewById(R.id.author_date_cv);
location = itemView.findViewById(R.id.location_cv);
description = itemView.findViewById(R.id.description_cv);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Detail Fragment:
public class FragmentDetail extends Fragment {
public FragmentDetail() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_detail, container, false);
}
}
I'd suggest a read on the documentation. Passing data between two activities should be done via interfaces.
As suggested by the official site

Using SearchView to retrieve matching values in Firebase database

I have an activity where I want to search matching values in my firebase database. I don't want anything to appear up until something is typed on my SearchBar, after something has been typed I want to display values that match what was typed in my SearchBar. I have created an activity and it is not displaying anything up until you type something, my problem is that it does not retrieve the matching values but it shows everything within my database directory.
This is my activity:
public class MyUsersActivity extends AppCompatActivit {
private Toolbar toolbar, searchtollbar;
private RecyclerView mUsersList;
private DatabaseReference mUsersDatabase;
private LinearLayoutManager mLayoutManager;
Menu search_menu;
MenuItem item_search;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//getSupportActionBar().setTitle("Search Users");
//toolbar.setTitleTextColor(android.graphics.Color.WHITE);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mLayoutManager = new LinearLayoutManager(this);
mUsersList = (RecyclerView) findViewById(R.id.users_list);
mUsersList.setHasFixedSize(true);
mUsersList.setLayoutManager(mLayoutManager);
setSearchtollbar();
}
#Override
protected void onStart() {
super.onStart();
}
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDisplayName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.user_single_name);
userNameView.setText(name);
}
public void setUserStatus(String status){
TextView userStatusView = (TextView) mView.findViewById(R.id.user_single_status);
userStatusView.setText(status);
}
public void setUserImage(String thumb_image, Context ctx){
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.user_single_image);
Picasso.with(ctx).load(thumb_image).placeholder(R.drawable.my_profile).into(userImageView);
}
}
public void setSearchtollbar()
{
searchtollbar = (Toolbar) findViewById(R.id.searchtoolbar);
if (searchtollbar != null) {
searchtollbar.inflateMenu(R.menu.menu_search);
search_menu=searchtollbar.getMenu();
searchtollbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
circleReveal(R.id.searchtoolbar,1,true,false);
else
searchtollbar.setVisibility(View.GONE);
}
});
item_search = search_menu.findItem(R.id.action_filter_search);
MenuItemCompat.setOnActionExpandListener(item_search, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
circleReveal(R.id.searchtoolbar,1,true,false);
}
else
searchtollbar.setVisibility(View.GONE);
return true;
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true;
}
});
initSearchView();
} else
Log.d("toolbar", "setSearchtollbar: NULL");
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void circleReveal(int viewID, int posFromRight, boolean containsOverflow, final boolean isShow)
{
final View myView = findViewById(viewID);
int width=myView.getWidth();
if(posFromRight>0)
width-=(posFromRight*getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material))-(getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material)/ 2);
if(containsOverflow)
width-=getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_overflow_material);
int cx=width;
int cy=myView.getHeight()/2;
Animator anim;
if(isShow)
anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0,(float)width);
else
anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, (float)width, 0);
anim.setDuration((long)220);
// make the view invisible when the animation is done
anim.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
if(!isShow)
{
super.onAnimationEnd(animation);
myView.setVisibility(View.INVISIBLE);
}
}
});
// make the view visible and start the animation
if(isShow)
myView.setVisibility(View.VISIBLE);
// start the animation
anim.start();
}
public void initSearchView()
{
final SearchView searchView = (SearchView) search_menu.findItem(R.id.action_filter_search).getActionView();
// Enable/Disable Submit button in the keyboard
searchView.setSubmitButtonEnabled(false);
// Change search close button image
ImageView closeButton = (ImageView) searchView.findViewById(R.id.search_close_btn);
closeButton.setImageResource(R.drawable.ic_close);
// set hint and the text colors
EditText txtSearch = ((EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text));
txtSearch.setHint("Search..");
txtSearch.setHintTextColor(Color.DKGRAY);
txtSearch.setTextColor(getResources().getColor(R.color.colorPrimary));
// set the cursor
AutoCompleteTextView searchTextView = (AutoCompleteTextView) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
try {
Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
mCursorDrawableRes.setAccessible(true);
mCursorDrawableRes.set(searchTextView, R.drawable.search_cursor); //This sets the cursor resource ID to 0 or #null which will make it visible on white background
} catch (Exception e) {
e.printStackTrace();
}
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
callSearch(query);
searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
callSearch(newText);
return true;
}
public void callSearch(String query) {
//Do searching
Log.i("query", "" + query);
if(!query.equals("")){
FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
Users.class,
R.layout.users_single_layout,
UsersViewHolder.class,
mUsersDatabase
) {
#Override
protected void populateViewHolder(UsersViewHolder usersViewHolder, Users users, int position) {
usersViewHolder.setDisplayName(users.getName());
usersViewHolder.setUserStatus(users.getStatus());
usersViewHolder.setUserImage(users.getThumb_image(), getApplicationContext());
final String user_id = getRef(position).getKey();
usersViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent profileIntent = new Intent(MyUsersActivity.this, ProfileActivity.class);
profileIntent.putExtra("user_id", user_id);
startActivity(profileIntent);
}
});
}
};
mUsersList.setAdapter(firebaseRecyclerAdapter);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_search:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
circleReveal(R.id.searchtoolbar,1,true,true);
else
searchtollbar.setVisibility(View.VISIBLE);
item_search.expandActionView();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
How can I implement the match function to retrieve what's matching in my database?

Android - Fragment not attached to activity

I have an activity which loads a fragment but when I press back button on the fragment it shows the error :-
"java.lang.IllegalStateException: Fragment ProductFragment{c46ba8a} not attached to Activity"
Code is below:-
Product Fragment:
public class ProductFragment extends Fragment implements TabLayout.OnTabSelectedListener, ViewPager.OnPageChangeListener {
private static final String PRODUCT_DATA = "product_data";
private TabLayout tabLayout;
private ViewPager viewPager;
NestedScrollView nestedScrollView;
//RecyclerView listView;
//ImageView ivHeader;
ProgressDialog pd;
Bundle bundle;
ViewPager viewPager1;
private LinearLayout pager_indicator;
public String DATA = "data";
public String PRODUCTS = "products";
//public String SPRODUCTS = "sproducts";
public String ID = "id";
public String NAME = "productName";
public String IMAGEURL = "productImg1";
public String DESCRIPTION = "description";
public String PRICE = "price";
public String DELIVERYTYPE = "deliverytype";
//String url = "https://chiraggohil.000webhostapp.com/product.php";
String url = "http://www.thinkdream.in/lunchbox2/product_api/getProductList";
String sliderImageUrl = "http://www.thinkdream.in/lunchbox2/assets/images/product/2.png";
ArrayList<Product> list = new ArrayList<>();
ArrayList<Product> sliderImagesList = new ArrayList<>();
private int dotsCount = 0;
private ImageView[] dots;
private static int CURRENT_PAGE = 0;
ViewPagerSliderAdapter viewPagerSliderAdapter;
ConnectivityManager cm;
NetworkInfo activeNetwork;
boolean isConnected;
//private boolean load = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_product, container, false);
viewPager1 = (ViewPager) v.findViewById(R.id.viewpager);
//listView = (RecyclerView) v.findViewById(R.id.gvProducts);
nestedScrollView = (NestedScrollView) v.findViewById(R.id.nestedSV);
pager_indicator = (LinearLayout) v.findViewById(R.id.viewPagerCountDots);
//nestedScrollView.setFillViewport(true);
//ivHeader = (ImageView) v.findViewById(R.id.ivHeader);
bundle = new Bundle();
tabLayout = (TabLayout) v.findViewById(R.id.tabLayout);
viewPager = (ViewPager) v.findViewById(R.id.pager);
viewPagerSliderAdapter = new ViewPagerSliderAdapter(getActivity(), sliderImagesList);
cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork = cm.getActiveNetworkInfo();
isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (savedInstanceState != null) {
sliderImagesList = savedInstanceState.getParcelableArrayList(PRODUCT_DATA);
viewPager1.setAdapter(viewPagerSliderAdapter);
viewPagerSliderAdapter.notifyDataSetChanged();
} else {
if (isConnected) {
new GetUrlData(getActivity()).execute();
} else {
Toast.makeText(getActivity(), "You are not connected to the internet!", Toast.LENGTH_SHORT).show();
}
}
tabLayout.addTab(tabLayout.newTab().setText("Pizza"));
tabLayout.addTab(tabLayout.newTab().setText("Sandwich"));
tabLayout.addTab(tabLayout.newTab().setText("Burger"));
Pager adapter = new Pager(getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(this);
viewPager1.addOnPageChangeListener(this);
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(PRODUCT_DATA, sliderImagesList);
}
#Override
public void onResume() {
super.onResume();
pager_indicator.removeAllViews();
//Picasso.with(getActivity()).load(sliderImageUrl).into(ivHeader);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
}
if (position >= dotsCount) {
dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
} else {
dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
private class GetUrlData extends AsyncTask<Void, Void, Void> {
GetUrlData(Context context) {
pd = new MyCustomProgressDialog(context, R.style.NewDialog);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setCancelable(false);
pd.show();
}
#Override
protected Void doInBackground(Void... voids) {
ServiceHandler sh = new ServiceHandler();
String result = sh.Getdata(url);
//list.clear();
sliderImagesList.clear();
if (result != null) {
try {
list.clear();
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray(DATA);
//JSONArray jsonArray = jsonObject1.getJSONArray(PRODUCTS);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
String id = jsonObject2.getString(ID);
String name = jsonObject2.getString(NAME);
String imgpath = jsonObject2.getString(IMAGEURL);
String desc = jsonObject2.getString(DESCRIPTION);
String price = jsonObject2.getString(PRICE);
//String deliverytype = jsonObject2.getString(DELIVERYTYPE);
Product product = new Product();
product.setId(id);
product.setProductName(name);
product.setProductImage(imgpath);
product.setProductDescription(desc);
product.setProductPrice(price);
//list.add(product);
sliderImagesList.add(product);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
pd.dismiss();
// Picasso.with(getActivity()).load(sliderImageUrl).into(ivHeader);
if(isAdded()) {
viewPagerSliderAdapter = new ViewPagerSliderAdapter(getActivity(), sliderImagesList);
Log.e("slider",sliderImagesList.toString());
viewPager1.setAdapter(viewPagerSliderAdapter);
viewPagerSliderAdapter.notifyDataSetChanged();
slider();
setUiPageViewController();
}else {
Log.e("not added","not added");
}
}
}
private void slider() {
int NUM_PAGES = sliderImagesList.size();
final android.os.Handler handler = new android.os.Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
CURRENT_PAGE = viewPager1.getCurrentItem();
if (CURRENT_PAGE == 2) {
CURRENT_PAGE = -1;
}
viewPager1.setCurrentItem(CURRENT_PAGE + 1, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(runnable);
}
}, 100, 4000);
}
private void setUiPageViewController() {
dotsCount = 3;
dots = new ImageView[dotsCount];
for (int i = 0; i < dotsCount; i++) {
dots[i] = new ImageView(getActivity());
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(4, 0, 4, 0);
pager_indicator.addView(dots[i], params);
}
dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
I don't know where I am wrong. I have searched for the error and even tried the solution from the link below:
Fragment MyFragment not attached to Activity
I ask questions on SO but I don't get response/answers. May be there is a small mistake, grammatical/formating problem, or a duplicate question but there is a possibility of my case that is different then others.
So please help and response.
Thanks.
--Edited--
HomeActivity :
public class HomeActivity extends AppCompatActivity implements View.OnClickListener {
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar toolbar;
TextView tvActionTitle;
SessionManager sessionManager;
GPSTracker gps;
int i = 0;
private FrameLayout redCircle;
private TextView countTextView;
int cartcount = 0;
Menu menu;
LunchBoxDB lunchBoxDB;
private String uid;
SharedPreferences pref;
private int totalquantity = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation);
tvActionTitle = (TextView) findViewById(R.id.tvActionTitle);
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/Quicksand_Bold_Oblique.otf");
tvActionTitle.setTypeface(custom_font);
setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayShowTitleEnabled(false);
lunchBoxDB = new LunchBoxDB(this);
pref = getSharedPreferences("loginPref", Context.MODE_PRIVATE);
uid = pref.getString("id", null);
ProductFragment pf = new ProductFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, pf).commit();
sessionManager = new SessionManager(this);
toolbar.setNavigationIcon(R.mipmap.ic_menu_white_24dp);
toolbar.setNavigationOnClickListener(this);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment frag = null;
int itemId = item.getItemId();
if (itemId == R.id.nav_home) {
drawerLayout.closeDrawers();
Intent i = new Intent(HomeActivity.this, HomeActivity.class);
startActivity(i);
HomeActivity.this.finish();
} else if (itemId == R.id.nav_profile) {
frag = new AccountFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, frag).addToBackStack("Account").commit();
drawerLayout.closeDrawers();
} else if (itemId == R.id.nav_order) {
drawerLayout.closeDrawers();
OrdersFragment of = new OrdersFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, of).addToBackStack("Orders").commit();
} else if (itemId == R.id.nav_store_locator) {
Intent i = new Intent(HomeActivity.this, LocationActivity.class);
startActivity(i);
drawerLayout.closeDrawers();
} else if (itemId == R.id.nav_logout) {
drawerLayout.closeDrawers();
sessionManager.logoutUser();
} else if (itemId == R.id.nav_help) {
drawerLayout.closeDrawers();
Intent i = new Intent(Intent.ACTION_DIAL);
i.setData(Uri.parse("tel:+918460765785"));
startActivity(i);
} else if (itemId == R.id.nav_corpinquiry) {
drawerLayout.closeDrawers();
CorpInquiryFragment crpf = new CorpInquiryFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, crpf).addToBackStack("CorpInquiry").commit();
}
return false;
}
});
}
private void setNavigationDrawer() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
drawerLayout.openDrawer(GravityCompat.START);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.nav_drawer, menu);
final MenuItem alertMenuItem = menu.findItem(R.id.shopping_bag);
FrameLayout rootView = (FrameLayout) alertMenuItem.getActionView();
redCircle = (FrameLayout) rootView.findViewById(R.id.view_alert_red_circle);
countTextView = (TextView) rootView.findViewById(R.id.view_alert_count_textview);
rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOptionsItemSelected(alertMenuItem);
}
});
badgeupdate();
return super.onCreateOptionsMenu(menu);
}
void badgeupdate() {
SQLiteDatabase db = lunchBoxDB.getReadableDatabase();
String query = "select sum(quantity) from cart where uid = " + uid;
Cursor c = db.rawQuery(query, null);
if (c != null && c.moveToFirst()) {
totalquantity = c.getInt(0);
}
c.close();
cartcount = totalquantity;
countTextView.setText(String.valueOf(cartcount));
redCircle.setVisibility((cartcount > 0) ? VISIBLE : GONE);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.shopping_bag) {
SharedPreferences pref = this.getSharedPreferences("couponPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("discount", null);
editor.apply();
CartFragment cf = new CartFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, cf, "CartFragment").addToBackStack(null).commit();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
}/*else if(i==0){
Toast.makeText(this, "Press back again to exit!", Toast.LENGTH_SHORT).show();
i=1;
}*/ else {
//i=0;
super.onBackPressed();
}
}
#Override
protected void onResume() {
super.onResume();
gps = new GPSTracker(this);
}
#Override
public void onClick(View view) {
setNavigationDrawer();
}
}
Logcat error :
FATAL EXCEPTION: main
Process: com.pisac.foodrestaurant, PID: 29700
java.lang.IllegalStateException: Fragment ProductFragment{13525074} not attached to Activity
at android.app.Fragment.getResources(Fragment.java:800)
at com.pisac.foodrestaurant.ProductFragment.onPageSelected(ProductFragment.java:149)
at android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1967)
at android.support.v4.view.ViewPager.scrollToItem(ViewPager.java:685)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:669)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:630)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:622)
at com.pisac.foodrestaurant.ProductFragment$1.run(ProductFragment.java:244)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5910)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
You have problem with the line
pd.dismiss();
in onPostExecute of your GetUrlData. Put it inside if (isAdded ()) As per the answer of the question you reffered in your question. Your dialog uses the context of the activity.
EDIT
Add an if block in onPageSelected method that checks if Fragment if attached i.e.
#Override
public void onPageSelected(int position) {
if(!isAdded ())
return;
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
}
if (position >= dotsCount) {
dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
} else {
dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
Thanks for helping me.
I got the answer.
I added onStop in the ProductFragment code as below :
#Override
public void onStop() {
viewPager1.setAdapter(null);
super.onStop();
}
and update the onResume :
#Override
public void onResume() {
super.onResume();
pager_indicator.removeAllViews();
if(viewPagerSliderAdapter==null){
new GetUrlData(getActivity()).execute();
}
}
Thanks once again.

How to get data from the db in activity a, when activity b is closed in Android with ActiveAndroid

im new to this and have some problems, thanks for your help.
Situation:
I have a MainActivity and a second Activity called MainAddMedActivity. I get data from the second activity through an EditText and save it in the database. My intention is to display the data from the EditText in a ListView in the MainActivity by taking it from the database. How to do it the right way ?
Med:
#Table(name = "Med")
public class Med extends Model {
// Zähler für eindeutige IDs
private static long counter = 0;
#Column(name = "_id", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
public long id;
#Column(name = "Description", index = true)
public String description;
public Med() {
super();
}
public Med(String message) {
super();
id = counter++;
description = message;
}
}
MedDAO:
public class MedDAO {
public static List<Med> getAll(String text) {
return new Select()
.from(Med.class)
.where("Description like ?", new String[]{'%' + text + '%'})
.orderBy("Description")
.limit(40)
.execute();
}
public static List<Med> getAll() {
return new Select()
.all()
.from(Med.class)
.execute();
}
public static List<Med> getOneItem(String text) {
return new Select()
.from(Med.class)
.where("Description = ?", text)
.execute();
}
public static void insertMed(String msg){
new Med(msg).save();
}
public static void remove(String text) {
new Delete().from(Med.class).where("Description = ?", text).execute();
}
}
MainActivity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ArrayAdapter<String> listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), MainAddMedActivity.class);
startActivity(intent);
}
});
ListView mainListView = (ListView) findViewById(R.id.listView);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = listAdapter.getItem(position);
//Aus DB entfernen
MedDAO.remove(item);
//Aus Liste im Gui entfernen
listAdapter.remove(item);
Toast.makeText(getBaseContext(), item + "gelöscht", Toast.LENGTH_SHORT).show();
}
});
//TODO: ArrayAdapter bugt
//Adapter für die Liste erzeugen
listAdapter = new ArrayAdapter<String>(this, R.layout.single_row, R.id.listMedNrPart);
mainListView.setAdapter(listAdapter);
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onResume() {
super.onResume();
// MedDAO.getLatestItem();
/*int max = listAdapter.getCount();
int i = 0;
while (i < max){
Log.d("MainActivity", listAdapter.getItem(i));
i++;
}*/
// listAdapter.add(MedDAO.getLatestItem().toString());
}
}
MainAddMedActivity:
public class MainAddMedActivity extends AppCompatActivity {
private EditText txtSearchMedicament;
private EditText txtNumberMedicament;
private TextView txtAlarmPrompt;
private TimePickerDialog timePickerDialog;
private Switch switchReminder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_add_med);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText description = (EditText) findViewById(R.id.txtSearchMedicament);
String text = description.getText().toString();
**//SAVE IN DATABASE**
MedDAO.insertMed(text);
//TODO: Close Activity
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
this.txtSearchMedicament = (EditText) findViewById(R.id.txtSearchMedicament);
this.txtNumberMedicament = (EditText) findViewById(R.id.txtNumberMedicament);
this.txtAlarmPrompt = (TextView) findViewById(R.id.txtAlarmPrompt);
this.switchReminder = (Switch) findViewById(R.id.switchReminder);
switchReminder.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cancelSwitch();
}
}
});
A Content Provider could be used. It takes a good amount of code to implement but it binds your database to your view.
Here is an example of a Content Provider I have implemented in the past.
You construct a ContentValue object (basically a set of values to mimic a database row) for your database keys and set your new data there. You then use getContentResolver() to insert the ContentValue into your Content Provider, which in turn updates your database with your new data.
ContentValues values = new ContentValues();
values.put(DatabaseHelper.KEY_VENUE_NAME, store.getName());
values.put(DatabaseHelper.KEY_VENUE_CITY, store.getCity());
values.put(DatabaseHelper.KEY_VENUE_STATE, store.getState());
//insert row
context.getContentResolver().insert(Uri.parse(ContentProvider.base_CONTENT_URI + index), values);
Here's an example of the Content Provider Class (too much code for here) which implements the logic for inserting, deleting, querying, editing, and constructing URI paths to your database.
You can then set up and use a Cursor, which iterates through your data source, to access the data from your Content Provider, more specifically you can extend CursorAdapter to directly bind your views to database queries. Here is what one looks like:
public class StoreCursorAdapter extends SimpleCursorAdapter {
private static final String TAG = "VenueCursorAdapter";
DatabaseHelper databaseHelper;
private Context context;
private int layout;
private int selection; //MapsActivity.getStoreSelection();
public StoreCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
databaseHelper = DatabaseHelper.getInstance(context);
this.context = context;
this.layout = layout;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(layout, parent, false);
return v;
}
#Override
public void bindView(View v, Context context, Cursor c) {
selection = ((MapsActivity) context).getStoreSelection();
int position = c.getPosition();
int nameColumn = c.getColumnIndex(DatabaseHelper.KEY_VENUE_NAME);
String name = c.getString(nameColumn);
TextView nameText = (TextView) v.findViewById(R.id.nameTextView);
TextView ratingText = (TextView) v.findViewById(R.id.ratingTextView);
if(nameText != null && ratingText != null) {
nameText.setText(name);
}
}
}

OnClickListener for launching webview from a listview row

A search api is returning me some meta data along with a URL "eventURL". I am placing the data in the listview, each row containing some data and a unique URL.I want when the user taps on the row in the listview,that unique URL should open in a webview.I have created a WebViewActivity for it,I am having issue with implementing the onClickListener.
MainActivity
public class MainActivity extends Activity {
//private EditText m_search_text;
private EditText m_zip;
private ListView m_search_results;
private Button m_search_btn;
private JSONArray m_results;
private LayoutInflater m_inflater;
private InputMethodManager m_ctrl;
private Spinner m_radius;
private Spinner m_activity_selector;
public static int radius = 0;
public static String activities;
static final private int EXIT_ID = Menu.FIRST;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// m_search_text = (EditText) findViewById(R.id.search_text);
m_zip = (EditText) findViewById(R.id.zip);
m_search_btn = (Button) findViewById(R.id.search_button);
// m_search_results = (ListView) findViewById(R.id.lview);
m_search_btn .setOnClickListener(go_handler);
m_ctrl = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
m_inflater = LayoutInflater.from(this);
addListenerOnSpinnerItemSelection();
addListenerOnSpinner1ItemSelection();
m_search_results = (ListView)findViewById(R.id.lview);
}
public void addListenerOnSpinnerItemSelection() {
m_radius = (Spinner) findViewById(R.id.spinner);
m_radius.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnSpinner1ItemSelection(){
m_activity_selector = (Spinner) findViewById(R.id.spinner1);
m_activity_selector.setOnItemSelectedListener(new ActivitySelectedListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
menu.add(0, EXIT_ID, 0, R.string.exit);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()){
case EXIT_ID:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
OnClickListener go_handler = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
m_ctrl.hideSoftInputFromWindow(m_zip.getWindowToken(), 0);
//String searchText = Uri.encode(m_search_text.getText().toString());
String zip = Uri.encode(m_zip.getText().toString());
new SearchTask().execute("?k=Fall+Classic" + "&m=meta:channel=" + activities + "&l="+ zip + "&r=" + radius);
// Show a toast showing the search text
Toast.makeText(getApplicationContext(),
getString(R.string.search_msg) + " " +
activities, Toast.LENGTH_LONG).show();
}
};
private class SearchTask extends AsyncTask<String, Integer, String>
{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(MainActivity.this,"","Please Wait...");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
String result = ActiveHelper.download(params [0]);
return result;
} catch (ApiException e) {
e.printStackTrace();
Log.e("alatta", "Problem making search request");
}
return "";
}
#Override
protected void onPostExecute(String result) {
dialog.hide();
try {
JSONObject obj = new JSONObject(result);
m_results = obj.getJSONArray("_results");
if (m_results == null ||m_results.length() == 0)
{
Toast.makeText(getApplicationContext(),
"No Results found for " + activities,
Toast.LENGTH_LONG).show();
}
else
m_search_results.setAdapter(new JSONAdapter(getApplicationContext()));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class JSONAdapter extends BaseAdapter
{
public JSONAdapter(Context c){
}
public int getCount()
{
return m_results.length();
}
public Object getItem(int arg0){
return null;
}
public long getItemId(int pos){
return pos;
}
public View getView(int pos, View convertView, ViewGroup parent) {
View tv;
TextView t;
if (convertView == null)
tv = m_inflater.inflate (R.layout.item, parent, false);
else
tv = convertView;
try {
/* For each entry in the ListView, we need to populate
* its text and timestamp */
t = (TextView) tv.findViewById(R.id.text);
JSONObject obj = m_results.getJSONObject(pos);
t.setText (obj.getString("title").replaceAll("\\<.*?\\>", ""));
t = (TextView) tv.findViewById(R.id.created_at);
JSONObject meta = obj.getJSONObject("meta");
t.setText ("When:" + "\t"+meta.getString("startDate")+"\n"+"Location:" +"\t" +meta.getString("location")+"\n" +"More Info:"+"\t" +meta.getString("eventURL")+"\n");
} catch (JSONException e) {
Log.e("alatta", e.getMessage());
}
return tv;
}
}}
WebViewActivity
public class WebViewActivity extends MainActivity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("url");
}}
Thanks.
You need to use OnItemClickListener:
MainActivity implements OnItemClickListener {
onCreate() {
m_search_results.setOnItemClickListener(this);
Make this method:
onItemClick(AdapterView<?> parent, View view, int position, long id) {
url = JSON.getHowever(position);
//get the intent, load the url, and launch the activity
}
You also need to handle the intent in your WebViewActivity, but that's beside the question

Categories

Resources