我是新手。
DictionaryDataHelper
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DictionaryDatabaseHelper extends SQLiteOpenHelper {
final static String DICTIONARY_DATABASE="dictionary";
final static String ITEM_ID_COLUMN="id";
final static String WORD_COLUMN="word";
final static String DEFINITION_COLUMN="definition";
final static String CREATE_DATABASE_QUERY="CREATE TABLE "+DICTIONARY_DATABASE+" ( "+
ITEM_ID_COLUMN+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
WORD_COLUMN+" TEXT , "+
DEFINITION_COLUMN+" TEXT)";
final static String ON_UPGRADE_QUERY="DROP TABLE "+DICTIONARY_DATABASE;
Context context;
public DictionaryDatabaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, DICTIONARY_DATABASE, factory, version);
this.context=context;
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(CREATE_DATABASE_QUERY);
}
@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
database.execSQL(ON_UPGRADE_QUERY);
onCreate(database);
}
public long insertData(WordDefinition wordDefinition) {
SQLiteDatabase database=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(WORD_COLUMN, wordDefinition.word);
values.put(DEFINITION_COLUMN, wordDefinition.definition);
return database.insert(DICTIONARY_DATABASE, null, values);
}
public long updateData(WordDefinition wordDefinition) {
SQLiteDatabase database=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(WORD_COLUMN, wordDefinition.word);
values.put(DEFINITION_COLUMN, wordDefinition.definition);
return database.update(DICTIONARY_DATABASE, values, WORD_COLUMN+" =?", new String[]{wordDefinition.word});
}
public void deleteData(WordDefinition wordDefinition) {
SQLiteDatabase database=this.getWritableDatabase();
String queryString="DELETE FROM "+DICTIONARY_DATABASE+" WHERE "+WORD_COLUMN+" = '"+wordDefinition.word+"'";
database.execSQL(queryString);
}
public ArrayList<WordDefinition> getAllWords() {
ArrayList<WordDefinition> arrayList=new ArrayList<WordDefinition>();
SQLiteDatabase database=this.getReadableDatabase();
String selectAllQueryString="SELECT * FROM "+DICTIONARY_DATABASE;
Cursor cursor=database.rawQuery(selectAllQueryString, null);
if (cursor.moveToFirst()) {
do {
WordDefinition wordDefinition=new WordDefinition(cursor.getString(cursor.getColumnIndex(WORD_COLUMN)), cursor.getString(cursor.getColumnIndex(DEFINITION_COLUMN)));
arrayList.add(wordDefinition);
} while (cursor.moveToNext());
}
return arrayList;
}
public WordDefinition getWordDefinition(String word) {
SQLiteDatabase database=this.getReadableDatabase();
WordDefinition wordDefinition=null;
String selectQueryString="SELECT * FROM "+DICTIONARY_DATABASE+ " WHERE "+WORD_COLUMN+" = '"+word+ "'";
Cursor cursor=database.rawQuery(selectQueryString, null);
if (cursor.moveToFirst()) {
wordDefinition=new WordDefinition(cursor.getString(cursor.getColumnIndex(WORD_COLUMN)), cursor.getString(cursor.getColumnIndex(DEFINITION_COLUMN)));
}
return wordDefinition;
}
public WordDefinition getWordDefinition(long id) {
SQLiteDatabase database=this.getReadableDatabase();
WordDefinition wordDefinition=null;
String selectQueryString="SELECT * FROM "+DICTIONARY_DATABASE+ " WHERE "+ITEM_ID_COLUMN+" = '"+id+ "'";
Cursor cursor=database.rawQuery(selectQueryString, null);
if (cursor.moveToFirst()) {
wordDefinition=new WordDefinition(cursor.getString(cursor.getColumnIndex(WORD_COLUMN)), cursor.getString(cursor.getColumnIndex(DEFINITION_COLUMN)));
}
return wordDefinition;
}
public void initializeDatabaseFortheFirstTime(ArrayList<WordDefinition> wordDefinitions) {
SQLiteDatabase database=this.getWritableDatabase();
database.execSQL("BEGIN");
ContentValues contentValues=new ContentValues();
for (WordDefinition wordDefinition : wordDefinitions) {
contentValues.put(WORD_COLUMN, wordDefinition.word);
contentValues.put(DEFINITION_COLUMN, wordDefinition.definition);
database.insert(DICTIONARY_DATABASE, null, contentValues);
}
database.execSQL("COMMIT");
}
}
DictionaryListActivity
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class DictionaryListActivity extends Activity {
TextView userTextView;
EditText searchEditText;
Button searchButton;
ListView dictionaryListView;
String logTagString="DICTIONARY";
ArrayList<WordDefinition> allWordDefinitions=new ArrayList<WordDefinition>();
DictionaryDatabaseHelper myDictionaryDatabaseHelper;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dictionary_list);
Log.d("DICTIONARY", "second activity started");
userTextView=(TextView) findViewById(R.id.personTextView);
userTextView.setText(getIntent().getStringExtra(MainActivity.USER_NAME_STRING));
searchEditText=(EditText) findViewById(R.id.searchEditText);
searchButton=(Button) findViewById(R.id.searchButton);
dictionaryListView=(ListView) findViewById(R.id.dictionaryListView);
myDictionaryDatabaseHelper=new DictionaryDatabaseHelper(this, "Dictionary", null, 1);
sharedPreferences=getSharedPreferences(MainActivity.SHARED_NAME_STRING, MODE_PRIVATE);
boolean initialized=sharedPreferences.getBoolean("initialized", false);
if (initialized==false) {
//Log.d(logTagString, "initializing for the first time");
initializeDatabase();
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putBoolean("initialized", true);
editor.commit();
}else {
Log.d(logTagString, "db already initialized");
}
allWordDefinitions=myDictionaryDatabaseHelper.getAllWords();
dictionaryListView.setAdapter(new BaseAdapter() {
@Override
public View getView(int position, View view, ViewGroup arg2) {
if (view==null) {
view=getLayoutInflater().inflate(R.layout.list_item, null);
}
TextView textView=(TextView) view.findViewById(R.id.listItemTextView);
textView.setText(allWordDefinitions.get(position).word);
return view;
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return allWordDefinitions.size();
}
});
dictionaryListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
Intent intent =new Intent(DictionaryListActivity.this, WordDefinitionDetailActivity.class);
intent.putExtra("word", allWordDefinitions.get(position).word);
intent.putExtra("definition", allWordDefinitions.get(position).definition);
startActivity(intent);
}
});
searchButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String string=searchEditText.getText().toString();
WordDefinition wordDefinition=myDictionaryDatabaseHelper.getWordDefinition(string);
if (wordDefinition==null) {
Toast.makeText(DictionaryListActivity.this, "Expressão não encontrada.", Toast.LENGTH_LONG).show();
}else {
Intent intent =new Intent(DictionaryListActivity.this, WordDefinitionDetailActivity.class);
intent.putExtra("word", wordDefinition.word);
intent.putExtra("definition", wordDefinition.definition);
startActivity(intent);
}
}
});
}
//
private void initializeDatabase() {
InputStream inputStream=getResources().openRawResource(R.raw.dictionary);
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
DictionaryLoader.loadData(bufferedReader, myDictionaryDatabaseHelper);
}
}
DictionaryLoader
package com.ecidioms;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class DictionaryLoader implements Comparator<WordDefinition> {
@Override
public int compare(WordDefinition A, WordDefinition B) {
return A.compareTo(B);
}
public static void loadData(BufferedReader bufferedReader, DictionaryDatabaseHelper dictionaryDatabaseHelper) {
ArrayList<WordDefinition> allWords=new ArrayList<WordDefinition>();
Collections.sort(allWords, new DictionaryLoader());
try {
BufferedReader fileReader=bufferedReader;
try {
int c=17;
c=fileReader.read();
while (c!=(-1)) {
StringBuilder stringBuilder=new StringBuilder();
while ((char)c!='\n'&&c!=-1) {
try {
stringBuilder.append((char)c);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(stringBuilder.length());
//e.printStackTrace();
}
c= fileReader.read();
if (c==-1) {
return;
}
}
String wordString=stringBuilder.toString();
ArrayList<String> definition=new ArrayList<String>();
while (c=='\n'||c=='\t') {
c= fileReader.read();
if (c=='\n'||c=='\t'||c=='\r') {
StringBuilder stringBuilder2=new StringBuilder();
while (c!='\n') {
stringBuilder2.append((char)c);
c=fileReader.read();
}
String definitionString=stringBuilder2.toString();
definition.add(definitionString);
}else {
break;
}
}
wordString=wordString.trim();
//Logger.log("word Loaded: "+(++counter)+" :"+wordString);
allWords.add(new WordDefinition(wordString, definition));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dictionaryDatabaseHelper.initializeDatabaseFortheFirstTime(allWords);
fileReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
WordDefinition
import java.util.ArrayList;
public class WordDefinition {
String word,definition;
public WordDefinition(String word,ArrayList<String> alldefinition) {
this.word=word;
StringBuilder stringBuilder=new StringBuilder();
for (String string : alldefinition) {
stringBuilder.append(string);
}
this.definition=stringBuilder.toString();
}
public WordDefinition(String word,String alldefinition) {
this.word=word;
this.definition=alldefinition;
}
}
WordDefinitionDetailActivity
import com.ecidioms.R;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class WordDefinitionDetailActivity extends Activity {
TextView wordTextView;
TextView definitionTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_word_definition_detail);
wordTextView=(TextView) findViewById(R.id.wordTextView);
definitionTextView=(TextView) findViewById(R.id.definitionTextView);
Log.d("DICTIONARY", "third activity started");
wordTextView.setText(getIntent().getStringExtra("word"));
definitionTextView.setText(getIntent().getStringExtra("definition"));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.word_definition_detail, menu);
return true;
}
}
答案 0 :(得分:1)
对所有WordDefinitions进行排序的最简单方法是创建一个这样的自定义比较器:
class DefinitionComparator implements Comparator<WordDefinition> {
@Override
public int compareTo(WordDefinition this, WordDefinition that) {
return this.getWord().compareTo(that.getWord());
}
}
然后使用返回的ArrayList(来自数据库)将自定义比较器的新实例传递给Collections.sort方法,如下所示:
Collections.sort(myWordDefinitionList, this);
修改强>
因此,您需要在WordDefinition类中添加单词和定义getter:
public String getWord() {
return this.word;
}
public String getDefinition() {
return this.definition;
}