Listview selected item highlight coming from database? - java

I am beginner in android creating religious book I have two activities both have listview the data is coming from sqlite database when i click any particular item from first activity switch to second activity show all detail in second activity which also have listview my question how to highlight second list item row only particular item is highlighted ! here example shown in picture what actually i want
here if anyone click on verse 13 all verse 1-25 is all show but only highlight verse 13 in next activity how this can be done here is my code
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class Chapters extends AppCompatActivity {
private ListView listView;
private ArrayList<String> stringArrayList;
private ArrayAdapter<String> adapter;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private int booknumber;
private String bookname;
TextView setbookname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapters);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setbookname=(TextView)findViewById(R.id.bookname);
Intent mIntent = getIntent();
booknumber= mIntent.getIntExtra("booknumber", 0);
bookname=mIntent.getStringExtra("bookname");
setbookname.setText(bookname);
toolbar.setTitle("");
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
Toast.makeText(this, ""+booknumber, Toast.LENGTH_SHORT).show();
setData();
listView =findViewById(R.id.list);
adapter = new ChapterAdopter(Chapters.this, R.layout.item_listview, stringArrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int chapternumber=position+1;
Toast.makeText(Chapters.this, ""+chapternumber, Toast.LENGTH_SHORT).show();
Intent intent=new Intent(Chapters.this,Verse.class);
intent.putExtra("Booknumber",booknumber);
intent.putExtra("Chapternumber",chapternumber);
startActivity(intent);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.chapter,menu);
MenuItem menuItem=menu.findItem(R.id.chapter_search);
SearchView searchView=(SearchView)menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
private void setData() {
stringArrayList = new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("select DISTINCT c from t_asv where b="+booknumber, new String[]{});
if(cursor!=null && cursor.getCount() > 0)
{
if (cursor.moveToFirst())
{
do {
stringArrayList.add(cursor.getString(0));
} while (cursor.moveToNext());
}
}
}
}
package bible.swordof.God;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class Verse extends AppCompatActivity {
private ListView listView;
private ArrayList<String> stringArrayList;
private ArrayAdapter<String> adapter;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private int booknumber;
private int chapternumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verse);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
Intent mIntent = getIntent();
booknumber = mIntent.getIntExtra("Booknumber", 0);
chapternumber= mIntent.getIntExtra("Chapternumber", 0);
toolbar.setTitle("");
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
setData();
listView = findViewById(R.id.list);
adapter = new VerseAdopter(Verse.this, R.layout.item_listview, stringArrayList);
Toast.makeText(this, ""+booknumber, Toast.LENGTH_SHORT).show();
listView.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.chapter, menu);
MenuItem menuItem = menu.findItem(R.id.chapter_search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
private void setData() {
stringArrayList = new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("select v FROM t_asv where b="+booknumber+" AND c="+chapternumber+";", new String[]{});
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
stringArrayList.add(cursor.getString(0));
} while (cursor.moveToNext());
}
}
}
}

It appears that you are passing the selected verse as a chapter and then in the query Cursor cursor = mDb.rawQuery("select v FROM t_asv where b="+booknumber+" AND c="+chapternumber+";", new String[]{}); therefore selecting all verses from the passed book/chapter.
You perhaps need to pass the clicked value as the verse as well as the book and chapter and use a query that includes the verse in the WHERE clause, perhaps cursor = mDb.rawQuery("select v FROM t_asv where b="+booknumber+" AND c="+chapternumber+" AND v=" + versenumber + " ;", new String[]{});

Related

RecyclerView search filter getting wrong position after filtering result

Hello friend please help me i am using Recylerview and implemented searchfilter but problem is that after searching the item in recylerview when i click on item it always return 0 position of the item i want actual position of list item please me help here is my code how get actual position recylerview after searching item in recylerview
here is my code
package bible.swordof.God;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SearchView.OnQueryTextListener {
private ListView listView;
private ArrayList<String> books;
private ArrayList<String> bookid;
private ListViewAdapter adapter;
private DatabaseHelper mDBHelper = null;
private SQLiteDatabase mDb = null;
BookRecyclerAdopter bookRecyclerAdopter;
//life is awesome
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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);
setData();
RecyclerView bookanme = findViewById(R.id.list);
bookanme.setLayoutManager(new LinearLayoutManager(this));
bookRecyclerAdopter = new BookRecyclerAdopter(this, books);
bookanme.setAdapter(bookRecyclerAdopter);
/* adapter = new ListViewAdapter(MainActivity.this, R.layout.item_listview, books, bookid);
listView.setAdapter(adapter);*/
/* listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int booknumber=position;
String bookname=bookid.get(position);
Toast.makeText(MainActivity.this, ""+bookname, Toast.LENGTH_SHORT).show();
*//* Intent intent=new Intent(MainActivity.this,Chapters.class);
intent.putExtra("booknumber",booknumber);
intent.putExtra("bookname",bookname);
startActivity(intent);*//*
}
});
}
*/
}
#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 onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search_voice_btn:
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, 10);
} else {
Toast.makeText(this, "Your Device Don't Support Speech Input", Toast.LENGTH_SHORT).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 10:
if (resultCode == RESULT_OK && data != null) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Toast.makeText(this, "" + result.get(0), Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(myActionMenuItem);
searchView.setOnQueryTextListener(this);
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment;
int id = item.getItemId();
if (id == R.id.home) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else if (id == R.id.favoruite) {
Intent intent = new Intent(this, Favourite.class);
startActivity(intent);
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setData() {
books = new ArrayList<>();
bookid = new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("select b,n from key_english", new String[]{});
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
books.add(cursor.getString(1));
bookid.add(cursor.getString(0));
} while (cursor.moveToNext());
}
}
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String newtext) {
String userinput = newtext.toLowerCase();
List<String> newlist = new ArrayList<>();
for (String name : books) {
if (name.toLowerCase().contains(userinput)) {
newlist.add(name);
}
}
bookRecyclerAdopter.updatelist(newlist);
return true;
}
}
package bible.swordof.God;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.util.ArrayList;
import java.util.List;
public class BookRecyclerAdopter extends RecyclerView.Adapter<BookRecyclerAdopter.Booksholder>{
private List<String> bookname;
Context context;
public BookRecyclerAdopter(Context context,List<String> bookname) {
this.bookname = bookname;
this.context=context;
}
public class Booksholder extends RecyclerView.ViewHolder {
private ImageView imageView;
private TextView bookname;
public Booksholder(#NonNull View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.image_view);
bookname = (TextView) itemView.findViewById(R.id.text);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
#Override
public Booksholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View view = inflater.inflate(R.layout.item_listview, viewGroup, false);
return new Booksholder(view);
}
#Override
public void onBindViewHolder(#NonNull Booksholder booksholder, final int i) {
booksholder.bookname.setText(bookname.get(i));
//get first letter of each String item
String firstLetter = String.valueOf(bookname.get(i).charAt(0));
ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
// generate random color
int color = generator.getColor(bookname.get(i));
TextDrawable drawable = TextDrawable.builder()
.buildRound(firstLetter, color); // radius in px
booksholder.imageView.setImageDrawable(drawable);
}
#Override
public int getItemCount() {
return bookname.size();
}
public void updatelist(List<String>newlist){
bookname=new ArrayList<>();
bookname.addAll(newlist);
notifyDataSetChanged();
}
}
You will need to maintain a separate list of bookname. Let's call it filteredBookname. Initially set it as bookname.
public class BookRecyclerAdopter extends RecyclerView.Adapter<BookRecyclerAdopter.Booksholder>{
private List<String> bookname;
private List<String> filteredBookname;
Context context;
public BookRecyclerAdopter(Context context,List<String> bookname) {
this.bookname = bookname;
this.filteredBookname = bookname
this.context=context;
}
...
// other pieces of code.
and instead of using bookname to populate RecyclerView items, use filteredBookname
and your update list method will be,
public void updatelist(List<String>newlist){
filteredBookname=new ArrayList<>();
filteredBookname.addAll(newlist);
notifyDataSetChanged();
}
Using the above approach, you can always find the proper position of your item in the original list bookname
The reason is that you are picking the wrong list, pick your data from filtered adapter list/model.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Books booksdata= (Books)adapterName.bookname.get(position);
Toast.makeText(MainActivity.this, ""+booksdata.bookname, Toast.LENGTH_SHORT).show();
Intent intent=new Intent(MainActivity.this,Chapters.class);
intent.putExtra("booknumber",booksdata.booknumber);
intent.putExtra("bookname",booksdata.bookname);
startActivity(intent);
}
});
}
holder.cardView_title.setOnClickListener {
when (holder.tv_number.text) {
"1" -> {
(context as Activity).startActivity(Intent(context, Ma1::class.java))
}
"2" -> {
(context as Activity).startActivity(Intent(context, Ma2::class.java))
}
"3" -> {
(context as Activity).startActivity(Intent(context, Ma3::class.java))
}
}
}

Why does my Header mix up the onClicklistener

When I add a header to my listview it messes up my onclick,it selects the wrong item every time.
package ie.example.artur.projectrepeat;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class DataListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ListView listView;
SQLiteDatabase sqLiteDatabase;
DatabaseClass database;
Cursor cursor;
ListDataAdapter listDataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_list_layout);
listView = (ListView) findViewById(R.id.list_view);
listDataAdapter = new ListDataAdapter(getApplicationContext(), R.layout.row_layout);
listView.setAdapter(listDataAdapter);
listView.setOnItemClickListener(this);
database = new DatabaseClass(getApplicationContext());
sqLiteDatabase = database.getReadableDatabase();
Cursor cursor=database.getInformation(sqLiteDatabase);
if (cursor.moveToFirst()) {
do {
String id, product_name, category,quantity,importance;
id = cursor.getString(0);
product_name = cursor.getString(1);
category = cursor.getString(2);
quantity = cursor.getString(3);
importance = cursor.getString(4);
DataProvider dataProvider = new DataProvider(id, product_name, category,quantity,importance);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
}
#Override
public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
final TextView tv = (TextView) view.findViewById(R.id.product_id);
AlertDialog.Builder alert = new AlertDialog.Builder(
DataListActivity.this);
alert.setTitle("Alert!!");
alert.setMessage("Are you sure to delete record");
alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//do your work here
sqLiteDatabase = database.getReadableDatabase();
DatabaseClass.DeleteInformation(tv.getText().toString(), sqLiteDatabase);
listView.setAdapter(listDataAdapter);
listDataAdapter.notifyDataSetChanged();
listDataAdapter.removeItemAt(position);
dialog.dismiss();
}
});
alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.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.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.
{
switch (item.getItemId())
{
case R.id.home : startActivity (new Intent(this, Main2Activity.class));
break;
case R.id.action_settings : startActivity (new Intent(this, SecondActivity.class));
break;
case R.id.catalogue :startActivity (new Intent(this, ViewAllItems.class));
break;
case R.id.ViewList :startActivity (new Intent(this, DataListActivity.class));
break;
case R.id.find :startActivity (new Intent(this, Main3Activity.class));
break;
case R.id.Update :startActivity (new Intent(this, Edit_Activity.class));
break;
}
return super.onOptionsItemSelected(item);
}}
}
When I add this code it messes up my app:
LayoutInflater myinflater = getLayoutInflater();
ViewGroup myHeader = (ViewGroup)myinflater.inflate(R.layout.header, listView, false);
listView.addHeaderView(myHeader, null, false)
The reason for that is that the header counts as additional one item inside your listview so when click on item you get the item in position - 1.
Add this inside onItemClick:
position -= listView.getHeaderViewsCount(); // or position - 1

Using SearchView on ListView with SimpleCursorAdapter

So I am trying to create a simple activity page that shows all contacts. Using the search view in the action bar, they should be able to filter the contacts. The contacts are correctly being populated into the ListView but the SearchView is not filtering the list. The list never updates.
This is my contacts activity:
package com.example.android.whereyouat;
import android.app.SearchManager;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.NavUtils;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Contacts extends AppCompatActivity {
Cursor cursor1;
SimpleCursorAdapter adapter;
SearchView searchView;
ListView lv;
MenuItem searchMenuItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
lv = (ListView) findViewById(R.id.list);
cursor1 = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
startManagingCursor(cursor1);
String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID};
int[] to = {android.R.id.text1, android.R.id.text2};
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, cursor1, from, to);
lv.setAdapter(adapter);
lv.setChoiceMode(lv.CHOICE_MODE_MULTIPLE);
lv.setTextFilterEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_contacts, menu);
searchMenuItem = menu.findItem(R.id.action_search);
searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem);
SearchManager SManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
android.support.v7.widget.SearchView searchViewAction = (android.support.v7.widget.SearchView) MenuItemCompat.getActionView(searchMenuItem);
searchViewAction.setSearchableInfo(SManager.getSearchableInfo(getComponentName()));
searchViewAction.setIconifiedByDefault(true);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.action_search:
//openSearch();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

Android Intent doesnt work

so I have these code
main.java
package com.example.kamusinggris_indonesiaidiom;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class Main extends Activity {
private TextView teks;
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
teks = (TextView) findViewById(R.id.text);
list = (ListView) findViewById(R.id.list);
}
protected void onNewIntent(Intent intent) {
handleIntent(getIntent());
}
private void handleIntent(Intent intent) {
// TODO Auto-generated method stub
handleIntent(intent);
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Intent wordIntent = new Intent(this, Definisi.class);
wordIntent.setData(intent.getData());
startActivity(wordIntent);
} else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
showResults(query);
}
}
private void showResults(String query) {
// TODO Auto-generated method stub
Cursor cursor = managedQuery(Provider.CONTENT_URI, null, null,
new String[] {query}, null);
if (cursor == null) {
// There are no results
teks.setText(getString(R.string.no_results, new Object[] {query}));
} else {
// Display the number of results
int count = cursor.getCount();
String countString = getResources().getQuantityString(R.plurals.search_results,
count, new Object[] {count, query});
teks.setText(countString);
// Specify the columns we want to display in the result
String[] from = new String[] { Database.KATA,
Database.DEFINISI };
// Specify the corresponding layout elements where we want the columns to go
int[] to = new int[] { R.id.kata,
R.id.definisi };
// Create a simple cursor adapter for the definitions and apply them to the ListView
SimpleCursorAdapter words = new SimpleCursorAdapter(this,
R.layout.hasil_pencarian, cursor, from, to);
list.setAdapter(words);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View tmp,
int posisi, long id) {
// TODO Auto-generated method stub
Intent definisi = new Intent(getApplicationContext(), Definisi.class);
Uri data = Uri.withAppendedPath(Provider.CONTENT_URI,
String.valueOf(id));
definisi.setData(data);
startActivity(definisi);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()) );
searchView.setIconifiedByDefault(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
onSearchRequested();
return true;
default:
return false;
}
}
}
definisi.java
package com.example.kamusinggris_indonesiaidiom;
import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.SearchView;
import android.widget.TextView;
public class Definisi extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_definisi);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
Uri uri = getIntent().getData();
Cursor kursor = managedQuery(uri, null, null, null, null);
if (kursor == null) {
finish();
} else {
kursor.moveToFirst();
TextView kata = (TextView) findViewById(R.id.kata);
TextView definisi= (TextView) findViewById(R.id.definisi);
int wIndex = kursor.getColumnIndexOrThrow(Database.KATA);
int dIndex = kursor.getColumnIndexOrThrow(Database.DEFINISI);
kata.setText(kursor.getString(wIndex));
definisi.setText(kursor.getString(dIndex));
} }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
onSearchRequested();
return true;
case android.R.id.home:
Intent a = new Intent(this, Main.class);
a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(a);
return true;
default:
return false;
}
}
}
its a dictionary, so when a search suggestion on a listview is clicked, it supposed to open the definisi.java and display the definition. But what I got here is when I clicked the search suggestion it displayed the main.java (its just go back to the previous activity). what's wrong on the intent part? please help me
Use passed intent variable in onNewIntent
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
You should also remove call to handleIntent from within handleIntent method

AdapterView.OnItemClickListener to pass to a new activity

I'm new to android programming and i need some help. I created a list, here is the code, and i want to pass to a new activity by clicking on an item in the list, can anybody suggest me how to do it step by step? Thanks!
package com.example.andrian.testapp;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.example.andrian.testapp.R;
public class MainActivity extends ActionBarActivity {
ListView listView ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
String[] values = new String[] {
"L0",
"L1",
"L2",
"L3",
"L4",
"L5",
"L6",
"L7"
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int itemPosition = position;
String itemValue = (String) listView.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
"Position: " + itemPosition + " List Item: " + itemValue, Toast.LENGTH_LONG)
.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.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Replace YOUR_ACTIVITY_NAME with the name of the new activity
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(),YOUR_ACTIVIY_NAME.class);
startActivity(intent);
}
});
Good luck.

Categories