Ich habe eine einfache Liste Anwendung mit einer Datenbank erstellt. Ich wollte hier die Funktionalität der Suche hinzufügen. Ich konnte die Suche implementieren, aber wenn ich auf das Objekt in der Suchliste klicke, öffnet es immer den Bildschirm des ersten Objekts in der Liste. Ich möchte die Details jeder Person in der Suchliste anklicken und anzeigen können. Bitte helfen ...Implementieren der Suche mit Datenbank in Android
Hauptaktivität
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.*;
import android.widget.*;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public static ArrayList<String> Array_Names= new ArrayList<String>();
MyDBHandler dbHandler;
MyDBHandler d1;
EditText searchtext;
ListView mylist;
ArrayAdapter<String> myAdapter;
private android.support.v7.widget.Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHandler = new MyDBHandler(this, null, null, 1);
d1= new MyDBHandler(this,null,null,1);
searchtext=(EditText)findViewById(R.id.searchtext);
/*dbHandler.addProduct(new Product("Mike", "222222222"));
dbHandler.addProduct(new Product("Ashley", "333333333"));
dbHandler.addProduct(new Product("Kevin", "444444444"));
dbHandler.addProduct(new Product("Nathan", "555555555"));*/
/*toolbar=(Toolbar)findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);*/
ScreenDetails();
}
public void ScreenDetails(){
dbHandler.getAllContacts();
mylist= (ListView)findViewById(R.id.mylist);
myAdapter= new CustomAdapter(this,Array_Names);
mylist.setAdapter(myAdapter);
searchtext.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
myAdapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
final Intent intent=new Intent(this,Display.class);
mylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
d1.addSortedProduct();
int pass_id=position+1;
Bundle data_bundle= new Bundle();
data_bundle.putInt("id",pass_id);
intent.putExtras(data_bundle);
startActivity(intent);
}
});
}
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 super.onCreateOptionsMenu(menu);
}
@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()) {
default:
return super.onOptionsItemSelected(item);
}
}
Produktklasse
public class Product {
private int _id;
private String _CName;
private String _phno;
public Product(){
}
public Product(String _CName, int _id, String _phno) {
this._CName = _CName;
this._id = _id;
this._phno = _phno;
}
public Product(String _CName, String _phno) {
this._CName = _CName;
this._phno = _phno;
}
public String get_CName() {
return _CName;
}
public void set_CName(String _CName) {
this._CName = _CName;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_phno() {
return _phno;
}
public void set_phno(String _phno) {
this._phno = _phno;
}
}
Database Handler
import android.database.sqlite.*;
import android.content.*;
import android.database.Cursor;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1; //Change whenever db is modified.
private static final String DATABASE_NAME = "List.db"; //Db name
public static final String TABLE_NAME = "CustomerList"; //Table Name
public static final String COLUMN_ID = "Id"; //Column Name
public static final String COLUMN_CNAME = "Name";
public static final String COLUMN_PHNO= "PhoneNumber";
public MyDBHandler(Context context, String name,SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION); //Context is always background info.
}
@Override
public void onCreate(SQLiteDatabase db) {
String query = " CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT " + " , " +
COLUMN_CNAME + " TEXT, " +
COLUMN_PHNO + " TEXT " +
"); ";
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(" DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void addProduct(Product product) {
ContentValues values = new ContentValues();
values.put(COLUMN_CNAME, product.get_CName());
values.put(COLUMN_PHNO,product.get_phno());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_NAME, null, values);
db.close();
}
public void removeProduct(String name) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL(" DELETE FROM " + TABLE_NAME + " WHERE " + COLUMN_CNAME + " =\" " + name + " \"; ");
}
public List<Product> getAllContacts(){
List<Product> contactList=new ArrayList<Product>();
SQLiteDatabase db= this.getWritableDatabase();
String Select_query= " SELECT * FROM " + TABLE_NAME + " ORDER BY " + COLUMN_CNAME;
Cursor cursor= db.rawQuery(Select_query,null);
if(cursor.moveToFirst()){
do {
Product contact= new Product();
contact.set_id(Integer.parseInt(cursor.getString(0)));
contact.set_CName(cursor.getString(1));
contact.set_phno(cursor.getString(2));
String name=cursor.getString(1) + "\n";
MainActivity.Array_Names.add(name);
contactList.add(contact);
}while (cursor.moveToNext());
}
return contactList;
}
public Product getProduct(String name){
SQLiteDatabase db=this.getWritableDatabase();
String query= "SELECT * FROM " + TABLE_NAME + " WHERE " + COLUMN_CNAME + "=\""+ name+"\"";
Cursor cursor=db.rawQuery(query,null);
Log.d("This is the Name",name);
Product product= new Product();
if(cursor.moveToFirst()){
cursor.moveToFirst();
product.set_id(Integer.parseInt(cursor.getString(0)));
product.set_CName((cursor.getString(1)));
product.set_phno(cursor.getString(2));
cursor.close();
}
db.close();
return product;
}
}
Display-Klasse
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class Display extends AppCompatActivity {
TextView pname;
TextView pno;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
Bundle main_data=getIntent().getExtras();
String message= main_data.getString("Name");
pname=(TextView)findViewById(R.id.pname);
pno=(TextView)findViewById(R.id.pno);
pname.setText(message);
MyDBHandler db=new MyDBHandler(this,null,null,1);
Product product= db.getProduct(pname.getText().toString());
pno.setText(product.get_phno());
}
}
Individuelle Adapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends ArrayAdapter<String> {
public CustomAdapter(Context context, ArrayList<String> names) {
super(context, R.layout.custom_list, names);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater myinflater= LayoutInflater.from(getContext());
View customView= convertView;
if(customView==null){
customView=myinflater.inflate(R.layout.custom_list,parent,false);
}
String singleItem=getItem(position);
TextView mytext=(TextView) customView.findViewById(R.id.name);
ImageView defimage=(ImageView) customView.findViewById(R.id.myimage);
mytext.setText(singleItem);
defimage.setImageResource(R.mipmap.contacts_default);
return customView;
}
}
Bündel extras = getIntent(). GetExtras(); id = extras.getInt ("id"); nametext = (Textansicht) findViewById (R.id.nametext); phoneno = (Textansicht) findViewById (R.id.phoneno); MyDBHandler db = neu MyDBBHandler (dies, null, null, 1); Cursorcursor = db.returnCursor (id); cursor.moveToFirst(); NAME = cursor.getString (Cursor.getColumnIndex (MyDBBHandler.COL_NAME)); NUMBER = cursor.getString (cursor.getColumnIndex (MyDBBHandler.COL_PHNO)); nametext.setText (NAME); phoneno.setText (NUMMER); } – Mehul
Ich änderte den Code für die Verwendung der zusätzlichen als die ID, die übergeben wird und nicht den Namen. Entschuldigung für diesen Fehler. Das Problem liegt jedoch immer noch darin, dass wenn ich den Namen Mike suche und ich auf das gesuchte Ergebnis von Mike klicke, öffnet sich der erste Kontakt in der ursprünglichen Liste, der alle Kontakte enthält. Ich kann nicht verstehen, wie ich damit umgehen soll. – Mehul
Ich bekomme nicht wirklich, was Sie wirklich erreichen wollen, aber ich kann Ihnen einen Rat geben. Sie sollten diese ID verwenden und dann einen Inhaltsanbieter verwenden: https://developer.android.com/guide/topics/providers/content-providers.html; Sie sollten das gewünschte Ergebnis in der Anzeigeaktivität erhalten. Verwenden Sie Ihre ID, um die Ergebnisse für diesen Kontakt abzufragen. – Lazai