祝你有个美好的一天。我正在学习Android开发,所以我正在创建一个简单的CRUD应用程序,现在我的主要活动是listview(MarcaActivity)和下一个代码:
package com.example.crudapp.activity;
import android.app.Activity;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.example.crudapp.MarcaCursorAdapter;
import com.example.crudapp.R;
import com.example.crudapp.cp.MarcaCP;
public class MarcaActivity extends Activity implements
LoaderManager.LoaderCallbacks<Cursor> {
MarcaCursorAdapter crsAdap;
ListView lstMarcas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_marca);
lstMarcas = (ListView)findViewById(R.id.lstMarcas);
lstMarcas.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent i = new Intent(MarcaActivity.this, MarcaDetailActivity.class);
Uri todoUri = Uri.parse(MarcaCP.CONTENT_URI + "/" + arg3);
i.putExtra("DET", todoUri);
i.putExtra("ACTION", "EXISTING");
startActivity(i);
}
});
getLoaderManager().initLoader(0, null, this);
fillData();
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
getLoaderManager().restartLoader(0, null, this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.insertMnu:
Intent i = new Intent(this, MarcaDetailActivity.class);
i.putExtra("ACTION", "NEW");
startActivityForResult(i, 0);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
/*switch (item.) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Uri uri = Uri.parse(MarcaCP.CONTENT_URI + "/"
+ info.id);
getContentResolver().delete(uri, null, null);
fillData();
return true;
}*/
return super.onContextItemSelected(item);
}
private void fillData() {
crsAdap = new MarcaCursorAdapter(this, R.layout.template_marcas, null ,
new String[]{MarcaCP.Marca.NOMBRE, MarcaCP.Marca.RANKING}, new int[]{R.id.nomMarca, R.id.rankMarca});
lstMarcas.setAdapter(crsAdap);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.marca, menu);
return true;
}
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
return new CursorLoader(this, MarcaCP.CONTENT_URI,
new String[]{MarcaCP.Marca.ID, MarcaCP.Marca.NOMBRE, MarcaCP.Marca.CODIGO, MarcaCP.Marca.RANKING}, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
crsAdap.swapCursor(arg1);
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
crsAdap.swapCursor(null);
} }
然后,我有管理详细视图的活动,我可以更新或添加项目,名为MarcaDetailActivity:
package com.example.crudapp.activity;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.crudapp.MarcaCursorAdapter;
import com.example.crudapp.R;
import com.example.crudapp.cp.MarcaCP;
public class MarcaDetailActivity extends Activity {
MarcaCursorAdapter crsAdap;
private Integer idReg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detalle_marca);
Bundle extras = getIntent().getExtras();
if(extras != null && extras.get("ACTION").equals("EXISTING")) //Invocamos fillData
fillData((Uri)extras.get("DET"));
else
cleanForm();
}
public void cleanForm() {
((Button)findViewById(R.id.todo_edit_button)).setVisibility(View.INVISIBLE);
((Button)findViewById(R.id.todo_insert_button)).setVisibility(View.VISIBLE);
}
public void fillData(Uri uri) {
String[] projection = { MarcaCP.Marca.CODIGO,
MarcaCP.Marca.CLASIFICACION, MarcaCP.Marca.NOMBRE, MarcaCP.Marca.RANKING};
//builder.
Cursor cur = getContentResolver().query(uri, projection, null, null, null);
if(cur != null) {
cur.moveToFirst();
((EditText)findViewById(R.id.detNombre)).setText(cur.getString(cur.getColumnIndex(MarcaCP.Marca.NOMBRE)));
((EditText)findViewById(R.id.detCodigo)).setText(cur.getString(cur.getColumnIndex(MarcaCP.Marca.CODIGO)));
setIdReg(cur.getInt(cur.getColumnIndex(MarcaCP.Marca.ID)));
((EditText)findViewById(R.id.todo_edit_button)).setVisibility(View.VISIBLE);
((EditText)findViewById(R.id.todo_insert_button)).setVisibility(View.INVISIBLE);
String clasif = cur.getString(cur.getColumnIndex(MarcaCP.Marca.CLASIFICACION));
int rank = cur.getInt(cur.getColumnIndex(MarcaCP.Marca.RANKING));
Spinner spRnk = ((Spinner)findViewById(R.id.detRanking));
Spinner spClasf = ((Spinner)findViewById(R.id.detClasificacion));
//Buscamos setear los spinners en sus valores
for(short ps = 0; ps < spRnk.getCount(); ps++) {
String tmpRnk = (String)spRnk.getItemAtPosition(ps);
if(tmpRnk.equalsIgnoreCase("" + rank))
spRnk.setSelection(ps);
}
//Buscamos setear los spinners en sus valores
for(short ps = 0; ps < spClasf.getCount(); ps++) {
String tmpClas = (String)spClasf.getItemAtPosition(ps);
if(tmpClas.equalsIgnoreCase(clasif))
spClasf.setSelection(ps);
}
cur.close();
}
}
private boolean validate() {
boolean res = true;
return res;
}
public void guardar(View view) {
if(validate()) {
ContentValues cv = new ContentValues();
cv.put(MarcaCP.Marca.CLASIFICACION, (String)((Spinner)findViewById(R.id.detClasificacion)).getSelectedItem() );
cv.put(MarcaCP.Marca.CODIGO, ((TextView)findViewById(R.id.detCodigo)).getText().toString() );
cv.put(MarcaCP.Marca.NOMBRE, ((TextView)findViewById(R.id.detNombre)).getText().toString() );
cv.put(MarcaCP.Marca.RANKING, Integer.parseInt("" + ((Spinner)findViewById(R.id.detRanking)).getSelectedItem() ));
getContentResolver().insert(MarcaCP.CONTENT_URI, cv);
}
Toast.makeText(MarcaDetailActivity.this, "Registro registrado",
Toast.LENGTH_SHORT).show();
//Refrescamos el grid y cerramos la actividad
//((MarcaActivity)this.getCallingActivity()).refrescarLista()
//getLoaderManager().restartLoader(0, null, MarcaActivity.class);
this.finish();
}
public void regresar() {
Intent i = new Intent(MarcaDetailActivity.this, MarcaActivity.class);
i.putExtra("REFRESH", true);
startActivity(i);
}
public void actualizar(View view) {
if(validate()) {
ContentValues cv = new ContentValues();
cv.put(MarcaCP.Marca.CLASIFICACION, (String)((Spinner)findViewById(R.id.detClasificacion)).getSelectedItem() );
cv.put(MarcaCP.Marca.CODIGO, (String)((TextView)findViewById(R.id.detCodigo)).getText() );
cv.put(MarcaCP.Marca.NOMBRE, (String)((TextView)findViewById(R.id.detNombre)).getText() );
cv.put(MarcaCP.Marca.ID, getIdReg() );
cv.put(MarcaCP.Marca.RANKING, Integer.parseInt("" + ((Spinner)findViewById(R.id.detRanking)).getSelectedItem() ));
getContentResolver().update(MarcaCP.CONTENT_URI, cv, null, null);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.marca, menu);
return true;
}
public Integer getIdReg() {
return idReg;
}
public void setIdReg(Integer idReg) {
this.idReg = idReg;
} }
正如您在MarcaDetailActivity的方法保护中所看到的,首先我使用我的自定义内容提供商插入项目,然后我使用Toast显示确认消息,最后完成活动,但是当我这样做时,listview isn& #39; t通过cursorloader刷新。我在这里阅读(stackoverflow)和其他我必须打电话的页面
getLoaderManager().restartLoader(LIST_ID, null, this);
但在我发现所有内容(在数据库中插入数据并刷新列表)的所有示例都在同一个活动中,但在这种情况下,我有一个列表活动和插入项目的第二个活动,所以我认为我必须从我的详细活动中调用restartLoader,但我不知道如何做到这一点,或者这是否是正确的方法。当我创建调用详细活动的意图并且有一个调用restartLoader的公共方法但我不知道这是否是最佳方法时,我正考虑在附加内容中保存对列表活动的引用。从我的详细活动中刷新光标加载器的最佳方法是什么?
我的内容提供商MarcaCP:
package com.example.crudapp.cp;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import com.example.crudapp.util.ConnHandler;
public class MarcaCP extends ContentProvider {
private static final int TODOS = 10;
private static final int TODO_ID = 20;
public static final Uri CONTENT_URI = Uri.parse("content://provider.marcacp/marcas");
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sURIMatcher.addURI("provider.marcacp", "marcas", TODOS);
sURIMatcher.addURI("provider.marcacp", "marcas" + "/#", TODO_ID);
}
public static class Marca {
public static final String TABLA = "MARCA";
public static final String ID = "_id";
public static final String CODIGO = "codigo";
public static final String NOMBRE = "nombre";
public static final String CLASIFICACION = "clasificacion";
public static final String RANKING = "ranking";
}
private ConnHandler conn;
SQLiteDatabase dbObj;
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int uriType = sURIMatcher.match(uri);
int rowsDeleted = 0;
switch (uriType) {
case TODOS:
rowsDeleted = dbObj.delete(Marca.TABLA, selection, selectionArgs);
break;
case TODO_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsDeleted = dbObj.delete(Marca.TABLA,
Marca.ID + " = " + id,
null);
} else {
rowsDeleted = dbObj.delete(Marca.TABLA,
Marca.ID + " =" + id
+ " and " + selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsDeleted;
}
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
int uriType = sURIMatcher.match(uri);
long id = 0;
switch (uriType) {
case TODOS:
id = dbObj.insert(Marca.TABLA, null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return Uri.parse("marca/" + id);
}
@Override
public boolean onCreate() {
conn = new ConnHandler(getContext());
dbObj = conn.getDb();
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// Uisng SQLiteQueryBuilder instead of query() method
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
checkColumns(projection);
queryBuilder.setTables(Marca.TABLA);
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case TODOS:
break;
case TODO_ID:
// Digamos para ver el detalle de un registro
queryBuilder.appendWhere(Marca.ID + " = "
+ uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Unknown URIx: " + uri);
}
Cursor cur = queryBuilder.query(dbObj, projection, selection,
selectionArgs, null, null, sortOrder);
return cur;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int uriType = sURIMatcher.match(uri);
int rowsUpdated = 0;
switch (uriType) {
case TODOS:
rowsUpdated = dbObj.update(Marca.TABLA,
values,
selection,
selectionArgs);
break;
case TODO_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsUpdated = dbObj.update(Marca.TABLA,
values,
Marca.ID + " =" + id,
null);
} else {
rowsUpdated = dbObj.update(Marca.TABLA,
values,
Marca.ID + " =" + id
+ " and "
+ selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
private void checkColumns(String[] projection) {
/*String[] available = { TodoTable.COLUMN_CATEGORY,
TodoTable.COLUMN_SUMMARY, TodoTable.COLUMN_DESCRIPTION,
TodoTable.COLUMN_ID };
if (projection != null) {
HashSet<String> requestedColumns = new HashSet<String>(Arrays.asList(projection));
HashSet<String> availableColumns = new HashSet<String>(Arrays.asList(available));
// Check if all columns which are requested are available
if (!availableColumns.containsAll(requestedColumns)) {
throw new IllegalArgumentException("Unknown columns in projection");
}
}*/
} }
它已在AndroidManifest.xml中注册:
<provider android:name=".cp.MarcaCP" android:authorities="provider.marcacp" />
问候。
答案 0 :(得分:0)
在完成第二项活动之前尝试getContentResolver().notifyChange(MarcaCP.CONTENT_URI, null, false)
。