在本文中,我们将详细介绍android–在其他活动中添加new后刷新SQLite列表的各个方面,并为您提供关于android刷新listview的相关解答,同时,我们也将为您带来关于AndroidMa
在本文中,我们将详细介绍android – 在其他活动中添加new后刷新SQLite列表的各个方面,并为您提供关于android刷新listview的相关解答,同时,我们也将为您带来关于Android Map V2地图在一项活动中加载,但在其他两项活动中未加载、Android SQLite事务处理结合Listview列表显示功能示例、android – ListView在添加到SQLiteDatabase时不刷新、android – RxJava – 等到重试完成其他活动/片段中的其他可观察对象的有用知识。
本文目录一览:- android – 在其他活动中添加new后刷新SQLite列表(android刷新listview)
- Android Map V2地图在一项活动中加载,但在其他两项活动中未加载
- Android SQLite事务处理结合Listview列表显示功能示例
- android – ListView在添加到SQLiteDatabase时不刷新
- android – RxJava – 等到重试完成其他活动/片段中的其他可观察对象
android – 在其他活动中添加new后刷新SQLite列表(android刷新listview)
我有两个活动 – 一个显示SQLite的数据,另一个在那里添加数据.我可以用标签在它们之间切换.问题是,如果我添加一个新项目,我不知道如何刷新列表,因为它在不同的活动类中,我无法在我的添加类中访问它.怎么解决这个问题?
这是我的两个班级:
列表:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
final Shoppingsql shoppingsql = new Shoppingsql(this);
final List<ShoppingData> list = shoppingsql.getAll();
final ArrayAdapter<ShoppingData> adapter = new ArrayAdapter<ShoppingData>(
this, android.R.layout.simple_list_item_1, list);
setlistadapter(adapter);
this.getListView().setLongClickable(true);
this.getListView().setonItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
shoppingsql.delete((int)list.get(position).getId());
adapter.remove(list.get(position));
adapter.notifyDataSetChanged();
return true;
}
});
}
加:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
}
public void ButtonOnClick(View v) {
Shoppingsql shoppingsql = new Shoppingsql(this);
ShoppingData data = new ShoppingData();
data.setName("test");
shoppingsql.add(data);
Dialog d = new Dialog(this);
d.setTitle("Added!");
d.show();
}
我也有一点问题.在我的第一个(列表)活动中,当我在“onLongClick”中访问它们时,Eclipse使每个变量都成为最终变量 – 为什么这样可以避免?此外,对我应该注意什么以及使我的代码更好或者我做的任何其他错误的任何评论都会非常好.
解决方法:
我会保持简单.只需将Add class中的intent发送到List类,然后再使用新项填充列表.
Android Map V2地图在一项活动中加载,但在其他两项活动中未加载
我是android map api v2的新手.我正在尝试在3种不同的活动(根据某些用户操作)中一张一张地加载地图.在1个活动中,地图加载正常,但仅使用缩放按钮仅显示灰色框.
以下是XML布局(map_view.xml),我正在使用include标记将其包括在三种不同的布局中.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp" >
<fragment
android:id="@+id/mapLocationDetail"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ImageView
android:id="@+id/transparent_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@android:color/transparent" />
<Button
android:id="@+id/btnRefresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="10dp"
android:layout_marginRight="10dp"
android:background="@drawable/btn_green_small"
android:text="Direction"
android:textColor="@color/white" />
</RelativeLayout>
以下是在一个活动中正确加载地图的代码.但别的2.
package com.nthreads.out2b.activity.places;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.nthreads.out2b.Out2B;
import com.nthreads.out2b.R;
public class LocationDetailActivity extends Out2B {
static final LatLng HAMBURG = new LatLng(53.558, 9.927);
static final LatLng KIEL = new LatLng(53.551, 9.993);
private GoogleMap map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_detail);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.mapLocationDetail))
.getMap();
Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG)
.title("Hamburg"));
Marker kiel = map.addMarker(new MarkerOptions()
.position(KIEL)
.title("Kiel")
.snippet("Kiel is cool")
.icon(BitmapDescriptorFactory
.fromresource(R.drawable.map_resturant_marker)));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
map.getUiSettings().setZoomControlsEnabled(false);
}
地图正确加载:
无法正确加载:
解决方法:
我找到了此问题的一些替代方法.您的代码看起来不错,这与代码或include标签没有什么关系.主要问题是制表符,我想您的地图在将其加载到活动中而不在制表符中时工作正常.因此,我建议使用视图分页器或使自己的控件显示为选项卡.地图将以这种方式工作.
Android SQLite事务处理结合Listview列表显示功能示例
本文实例讲述了Android sqlite事务处理结合Listview列表显示功能。分享给大家供大家参考,具体如下:
前面的文章里介绍过事务的特点如原子性,隔离性,一致性,持久性。下面就结合Android的sqlite来说下,这次的文章里会把listview也结合起来用。实际上android里的事务和我们数据库里的是一样的。也是开启事务,操作,提交事务。如果出现问题就回滚。
public void Transaction(){ sqliteDatabase database=db.getReadableDatabase(); database.beginTransaction(); //开启事务 try{ String sql1="update student set username='lili' where userid=2"; String sql2="update student set username='lucy' where userid=3"; database.execsql(sql1); database.execsql(sql2); database.setTransactionSuccessful(); //设置事务的状态,这句不写事务就会回滚 }finally{ database.endTransaction(); //结束事务 } }
上面这段代码就是一个简单的事务操作,需要注意的就是要捕获异常,这样事务就会被结束掉可以节约数据库资源。
事务的操作就是这样,下面就介绍下listview的使用,我们理解成列表就可以了。界面如下
我们可以把这个界面拆成2个,主界面就只有“用户id”,“用户名”,“用户住址”也就是列表的头,主界面如下
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:layout_width="60dip" android:layout_height="wrap_content" android:text="用户id" /> <TextView android:layout_width="60dip" android:layout_height="wrap_content" android:text="用户名" /> <TextView android:layout_width="60dip" android:layout_height="wrap_content" android:text="用户住址" /> </LinearLayout> <ListView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/listview" /> </LinearLayout>
这里的listview要定义一个id提供后面数据绑定使用,含有内容的显示界面也比较简单,也就是几个textview
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:layout_width="60dip" android:layout_height="wrap_content" android:id="@+id/userid" /> <TextView android:layout_width="60dip" android:layout_height="wrap_content" android:id="@+id/username" /> <TextView android:layout_width="90dip" android:layout_height="wrap_content" android:id="@+id/address" /> </LinearLayout>
这样界面的部分就OK了,接下来就是读取数据了,之后显示在listview中,在这里就提供2种方法来显示数据
(1)方法1
package org.lxh.db; import java.util.*; import org.lxh.service.StudentService; import org.lxh.vo.Student; import android.app.Activity; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.SimpleCursorAdapter; import android.widget.Toast; public class DBActivity extends Activity { private StudentService service; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); this.service=new StudentService(this); ListView view=(ListView)this.findViewById(R.id.listview); List<Student> all=this.service.fiandAll(); List<HashMap<String,Object>> data=new ArrayList<HashMap<String,Object>>(); //逐个取出元素 Iterator<Student> it=all.iterator(); Student stu=null; while(it.hasNext()){ stu=new Student(); stu=it.next(); HashMap<String,Object> map=new HashMap<String,Object>(); map.put("userid",stu.getUserid()); map.put("username",stu.getUsername()); map.put("address",stu.getAddress()); data.add(map); } //数据绑定 SimpleAdapter adapter=new SimpleAdapter(this,data,R.layout.listview,new String[]{"userid","username","address"},new int[]{R.id.userid,R.id.username,R.id.address}); view.setAdapter(adapter); //添加列表项监听事件 view.setonItemClickListener(new OnItemClickListener(){ public void onItemClick(AdapterView<?> parent,View view,int position,long id) { ListView listview=(ListView)parent; HashMap<String,Object> hash=(HashMap<String,Object>)listview.getItemAtPosition(position); Toast.makeText(DBActivity.this,hash.get("userid").toString(),1).show(); }}); }
这里的数据绑定,使用的是SimpleAdapter,我们首先要做的就是把数据逐个取出来存入一个HashMap,如下所示
HashMap<String,Object>();
这里的hashmap存储的是泛型数据,这个集合的泛型不能随便修改,接下来的工作就是把这个集合当做list的泛型
List<HashMap<String,Object>>();
最后要记得把这个map添加到集合里
对于
SimpleAdapter adapter=new SimpleAdapter(this,R.id.address}); view.setAdapter(adapter);
第四个参数里的"userid","address"是map集合里的key,最后一个参数是textview,也就是数据界面里的textview.后面还加了个监听,只要点击textview就会显示用户id,android就会通过textview的位置读取内容。
这里把先读数据的代码先贴出来
public List<Student> fiandAll(){ List<Student> all=new ArrayList<Student>(); String sql="select * from student"; sqliteDatabase database=db.getReadableDatabase(); //使用getReadableDatabase取得sqliteDatabase Cursor cursor=database.rawQuery(sql,null); //得到游标,类似resultset Student stu; while(cursor.movetoNext()){ //移动游标 int id=cursor.getInt(cursor.getColumnIndex("userid")); String name=cursor.getString(cursor.getColumnIndex("username")); String address=cursor.getString(cursor.getColumnIndex("address")); stu=new Student(); stu.setUserid(id); stu.setUsername(name); stu.setAddress(address); all.add(stu); } cursor.close(); //关闭游标 return all; }
(2)游标适配器
下面是读数据的代码
public Cursor fiandAllCursor(){ List<Student> all=new ArrayList<Student>(); String sql="select userid as _id,username,address from student"; sqliteDatabase database=db.getReadableDatabase(); //使用getReadableDatabase取得sqliteDatabase Cursor cursor=database.rawQuery(sql,类似resultset //cursor.close(); //这里不可以关闭游标 return cursor; }
这里为主键的列取了别名是因为android内部建议主键设置为_id,但是不可能每个表的主键的名称都是_id
Cursor all=this.service.fiandAllCursor(); //使用游标适配器 SimpleCursorAdapter cadapter=new SimpleCursorAdapter(this,all,new String[]{"_id",R.id.address}); view.setAdapter(cadapter); //添加列表项监听事件 view.setonItemClickListener(new OnItemClickListener(){ public void onItemClick(AdapterView<?> parent,long id) { ListView listview=(ListView)parent; Cursor hash=(Cursor)listview.getItemAtPosition(position); //取得被点击item的位置 int temp=hash.getInt(hash.getColumnIndex("_id")); Toast.makeText(DBActivity.this,String.valueOf(temp),1).show(); }});
这里的适配器参数顺序和上面的有点不同,而且第四个参数里的“usernam”,"address"和'_id'都是表的列名。其他地方没太大区别,上面的“_id”也不能写成别的。否则会出错
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android操作SQLite数据库技巧总结》、《Android数据库操作技巧总结》、《Android编程之activity操作技巧总结》、《Android文件操作技巧汇总》、《Android开发入门与进阶教程》、《Android资源操作技巧汇总》、《Android视图View技巧总结》及《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。
android – ListView在添加到SQLiteDatabase时不刷新
每当我向sqliteDatabase添加内容时,ListView都不会显示它,但如果我完全重新启动应用程序,它就会显示.这是我的主要.java:
package com.gantt.shoppinglist;
import android.app.Dialog;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.sqliteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class ShoppingList extends ListActivity {
SimpleCursorAdapter adapter = null;
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final DataHelper dataHelper = new DataHelper(this);
ListView lv = (ListView) findViewById(android.R.id.list);
final sqliteDatabase db = dataHelper.selectAll();
final Cursor c = db.rawQuery("SELECT disTINCT oid as _id,name FROM table1 ORDER BY name", null);
if (c.movetoFirst()) {
String[] columnNames = new String[]{"name"};
int[] text1 = new int[]{android.R.id.text1};
adapter = new SimpleCursorAdapter(this, R.layout.rowlayout, c, columnNames, text1);
}
lv.setAdapter(adapter);
Button button1main = (Button) findViewById(R.id.add);
button1main.setonClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final Dialog additem = new Dialog(ShoppingList.this);
additem.setContentView(R.layout.maindialog);
final EditText et = (EditText)additem.findViewById(R.id.edittext);
additem.setTitle("Type your item");
additem.setCancelable(true);
et.setHint("Type the name of an item...");
Button button = (Button) additem.findViewById(R.id.cancel);
button.setonClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
additem.dismiss();
}
});
additem.show();
Button ok = (Button) additem.findViewById(R.id.ok);
ok.setonClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
addItems();
}
private void addItems() {
String item = et.getText().toString();
dataHelper.insert(item);
c.requery();
db.close();
additem.dismiss();
et.setText("");
}
});
}
});
}
}
我的DataHelper类:
package com.gantt.shoppinglist;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.sqliteDatabase;
import android.database.sqlite.sqliteOpenHelper;
import android.database.sqlite.sqliteStatement;
import android.util.Log;
public class DataHelper {
public static final String DATABASE_NAME = "items.db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "table1";
public static final String KEY_ROWID = "_id";
private Context context;
private sqliteDatabase db;
private sqliteStatement insertStmt;
private static final String INSERT = "insert into "
+ TABLE_NAME + "(name) values (?)";
public DataHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
this.insertStmt = this.db.compileStatement(INSERT);
}
public long insert(String name) {
this.insertStmt.bindString(1, name);
return this.insertStmt.executeInsert();
}
public void deleteall() {
this.db.delete(TABLE_NAME, null, null);
}
public sqliteDatabase selectAll() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name" },
null, null, null, null, "name desc");
if (cursor.movetoFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.movetoNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return db;
}
public static String getDatabaseName() {
return DATABASE_NAME;
}
private static class OpenHelper extends sqliteOpenHelper {
OpenHelper(Context context) {
super(context, getDatabaseName(), null, DATABASE_VERSION);
}
@Override
public void onCreate(sqliteDatabase db) {
db.execsql("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, name TEXT");
}
@Override
public void onUpgrade(sqliteDatabase db, int oldVersion, int newVersion) {
Log.w("Example", "Upgrading database, this will drop tables and recreate.");
db.execsql("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
解决方法:
您需要在Cursor上调用requery(),而不是在Adapter上调用changeCursor()和notifyDataSetChanged(). Here is a sample project展示了这一点.
android – RxJava – 等到重试完成其他活动/片段中的其他可观察对象
用例:我正在开发一个Android应用程序,其中有一个包含4个选项卡的viewpager,所有这些都是片段.对于每个选项卡/片段,我必须每隔5分钟连接一个具有Oauth和令牌到期的REST Api.
当前解决方案:使用RxJava并重试当操作符我可以在收到401 HTTP错误时重新进行身份验证.对于订阅和使用的每个Observable流,使用:
retrywhen(refreshTokenAuthenticator)
因此,当令牌过期时,流消耗它然后执行真正的api调用.
问题:这仅适用于在一个订阅中消费的一个观察者,但是我需要允许用户在标签之间切换而不阻止他/她考虑到401错误可以在任何Api呼叫中的任何片段中随时出现.
问题:有没有办法让observables等待其他observable完成onNext()不在同一个流/订阅者中?实际上在不同的碎片?所以api调用场景将是这样的:
Api Call Fragment A --> request
Api Call Fragment A <-- response 200 Code
Api Call Fragment B --> request
Api Call Fragment B <-- response 401 Code (retrywhen in action)
Api Call Fragment B --> request (refreshToken)
Api Call Fragment B <-- response 200 (with new access token saved in the app)
几乎在同一时间……
Api Call Fragment C --> request
Api Call Fragment C <-- response 401 Code (retrywhen in action)
Observable in Fragment C Waits till Observable in Fragment B finish (onNext())
Api Call Fragment C --> request
Api Call Fragment C <-- response 200
这就是我已经拥有的,每个API调用看起来几乎相同:
public void getDashboardDetail() {
Subscription subscription = repository.getDashboard()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.retrywhen(tokenAuthenticator)
.subscribe(new RestHttpObserver<UserDataDto>() {
@Override
public void onUnkNownError(Throwable e) {
getMvpView().onError(e);
}
@Override
public void onHostUnreachable() {
getMvpView().onHostUnreachable();
}
@Override
public void onHttpErrorCode(int errorCode, ErrorDto errorDto) {
getMvpView().onHttpErrorCode(errorCode, errorDto);
}
@Override
public void onCompleted() {
//Do nothing...
}
@Override
public void onNext(UserDataDto response) {
getMvpView().onReceiveUserData(response);
}
});
this.compositeSubscription.add(subscription);
}
我的RefreshTokenAuthenticator:
public class RefreshTokenAuthenticator implements Func1<Observable<? extends Throwable>, Observable<?>> {
private static final int RETRY_COUNT = 1;
private static final int HTTP_ERROR_CODE = 401;
@Inject
private UserRepository repository;
@Inject
private SessionManager sessionManager;
@Inject
private MyApplication application;
@Inject
private RefreshTokenAuthenticator() {
}
@Override
public synchronized Observable<?> call(Observable<? extends Throwable> observable) {
return observable
.flatMap(new Func1<Throwable, Observable<?>>() {
int retryCount = 0;
@Override
public Observable<?> call(final Throwable throwable) {
retryCount++;
if (retryCount <= RETRY_COUNT && throwable instanceof HttpException) {
int errorCode = ((HttpException) throwable).code();
if (errorCode == HTTP_ERROR_CODE) {
return repository
.refreshToken(sessionManager.getAuthToken().getRefreshToken())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.doOnNext(tokenDto -> sessionManager.saveAuthToken(tokenDto))
.doOnError(throwable1 -> {
Log.e("RefreshTokenAuth", "DoOnError", throwable1);
application.logout();
});
}
}
// No more retries. Pass the original Retrofit error through.
return Observable.error(throwable);
}
});
}
}
解决方法:
1)使auth令牌缓存的上一次成功结果提供方法使此缓存结果无效:
class Auth {
private Observable<AuthToken> validToken;
synchronized void invalidateAuthToken() {
validToken = null;
}
synchronized Observable<AuthToken> getAuthToken() {
if (validToken == null) {
validToken = repository
.refreshToken(...) // start async request
.doOnError(e -> invalidateAuthToken())
.replay(1); // cache result
}
return validToken; // share among all subscribers
}
}
2)要访问Web服务,请使用以下模式:
Observable<Data1> dataSource1 =
Observable.defer(auth.getAuthToken()) // always start from token
.flatMap(token ->
repository.fetchData1(token, ...)) // use token to call web service
.doOnError(e -> auth.invalidateAuthToken())
.retry(N); // retry N times
关于android – 在其他活动中添加new后刷新SQLite列表和android刷新listview的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于Android Map V2地图在一项活动中加载,但在其他两项活动中未加载、Android SQLite事务处理结合Listview列表显示功能示例、android – ListView在添加到SQLiteDatabase时不刷新、android – RxJava – 等到重试完成其他活动/片段中的其他可观察对象的相关信息,请在本站寻找。
本文标签: