我有一个列表适配器。我试图优先保存列表项,并在重新启动手机期间回拨onCreate,这样我就不会丢失任何列表项。现在在onCreate期间我正在检查适配器是否为空。这工作正常,但从Preferences中调用值给出以下错误。谁能猜到什么是错误?以下是错误和代码:
编辑问题并添加提交零件类代码。您可以在评论“/ 日志成功推送报告 /”
之间找到提交错误:
11-18 12:42:25.740: E/AndroidRuntime(7264): FATAL EXCEPTION: main
11-18 12:42:25.740: E/AndroidRuntime(7264): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.teleca.sam.engine/com.teleca.sam.ui.LogListView}: java.util.NoSuchElementException
11-18 12:42:25.740: E/AndroidRuntime(7264): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
11-18 12:42:25.740: E/AndroidRuntime(7264): at android.app.ActivityThread.startActivityNow(ActivityThread.java:1941)
11-18 12:42:25.740: E/AndroidRuntime(7264): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
11-18 12:42:25.740: E/AndroidRuntime(7264): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
11-18 12:42:25.740: E/AndroidRuntime(7264): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:705)
11-18 12:42:25.740: E/AndroidRuntime(7264): at android.widget.TabHost.setCurrentTab(TabHost.java:369)
11-18 12:42:25.740: E/AndroidRuntime(7264): at android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:150)
11-18 12:42:25.740: E/AndroidRuntime(7264): at android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:560)
11-18 12:42:25.740: E/AndroidRuntime(7264): at android.view.View.performClick(View.java:4223)
11-18 12:42:25.740: E/AndroidRuntime(7264): at android.view.View$PerformClick.run(View.java:17275)
11-18 12:42:25.740: E/AndroidRuntime(7264): at android.os.Handler.handleCallback(Handler.java:615)
11-18 12:42:25.740: E/AndroidRuntime(7264): at android.os.Handler.dispatchMessage(Handler.java:92)
11-18 12:42:25.740: E/AndroidRuntime(7264): at android.os.Looper.loop(Looper.java:137)
11-18 12:42:25.740: E/AndroidRuntime(7264): at android.app.ActivityThread.main(ActivityThread.java:4898)
11-18 12:42:25.740: E/AndroidRuntime(7264): at java.lang.reflect.Method.invokeNative(Native Method)
11-18 12:42:25.740: E/AndroidRuntime(7264): at java.lang.reflect.Method.invoke(Method.java:511)
11-18 12:42:25.740: E/AndroidRuntime(7264): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
11-18 12:42:25.740: E/AndroidRuntime(7264): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
11-18 12:42:25.740: E/AndroidRuntime(7264): at dalvik.system.NativeStart.main(Native Method)
11-18 12:42:25.740: E/AndroidRuntime(7264): Caused by: java.util.NoSuchElementException
11-18 12:42:25.740: E/AndroidRuntime(7264): at java.util.StringTokenizer.nextToken(StringTokenizer.java:208)
11-18 12:42:25.740: E/AndroidRuntime(7264): at com.teleca.sam.ui.LogListView.onCreate(LogListView.java:71)
11-18 12:42:25.740: E/AndroidRuntime(7264): at android.app.Activity.performCreate(Activity.java:5206)
11-18 12:42:25.740: E/AndroidRuntime(7264): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
11-18 12:42:25.740: E/AndroidRuntime(7264): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
11-18 12:42:25.740: E/AndroidRuntime(7264): ... 18 more
11-18 12:42:25.770: E/android.os.Debug(2281): !@Dumpstate > dumpstate -k -t -z -d -o /data/log/dumpstate_app_error
代码:
public class LogListView extends ListActivity {
/** Called when the activity is first created. */
private static String newString;
private static EntryAdapter adapter;
int clickCounter = 0;
static ArrayList<Item> items = new ArrayList<Item>();
static SharedPreferences preferences = null;
private static Context context = null;
static StringTokenizer tokens;
private static String first;
private static String second;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
adapter = new EntryAdapter(this, items);
//items.add(new SectionItem("Log Report"));
setListAdapter(adapter);
if(adapter.getCount()!=0){
//Do nothing Adapter has value
}else {
Toast.makeText(LogListView.this, "No Items Available",Toast.LENGTH_SHORT).show();
addItems();
}
}
// Method which will handle dynamic insertion
public static void addItems() {
preferences = context.getSharedPreferences("LOG",
android.content.Context.MODE_PRIVATE);
newString = preferences.getString("log", "");
tokens = new StringTokenizer(newString, ",");
first = tokens.nextToken();
second = tokens.nextToken();
items.add(new EntryItem(first, second));
adapter.notifyDataSetChanged();
}
// Method which will handle dynamic insertion ends
@Override
public void onResume() {
super.onResume();
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
if (!items.get(position).isSection()) {
EntryItem item = (EntryItem) items.get(position);
// Toast.makeText(this, "You clicked " + item.title ,
// Toast.LENGTH_SHORT).show();
Toast.makeText(this, "You clicked " + position, Toast.LENGTH_SHORT)
.show();
}
if (position == 9) {
}
super.onListItemClick(l, v, position, id);
}
提交完成的类
public class Support extends TabActivity {
// private ImageView mSpinnerImage = null;
// private Animation mAnimation = null;
private Button syncbutton = null;
private TextView synctitle = null;
private Button home = null;
private Button messages = null;
private Button history = null;
private Button settings = null;
private Button support = null;
private TabHost mTabHost = null;
private Preferences prefs = Preferences.getInstance();
private Context context = null;
private SharedPreferences eulapreferences = null;
private boolean vpnenableboolean = false;
private Editor defaultprefsedit = null;
private int acrTransmissionRate = 0;
private long shortsleeptime = 0;
private static final String PREFERENCE_EULA_ACCEPTED = "eula.accepted";
private static final String PREFERENCES_EULA = "eula";
private SharedPreferences defaultprefs = null;
private int vpnenable;
public static int data_reset = 0;
private String appVersion;
private static int currentapiVersion = android.os.Build.VERSION.SDK_INT;
private String strName;
private SimpleDateFormat s;
private String format;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Titlebar + Button */
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.support);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.window_title);
syncbutton = (Button) findViewById(R.id.syncbutton);
/*Reset Service Parameters*/
context = this;
prefs = Preferences.getInstance();
eulapreferences = getSharedPreferences(PREFERENCES_EULA, Activity.MODE_PRIVATE);
defaultprefs = PreferenceManager.getDefaultSharedPreferences(context);
defaultprefsedit = defaultprefs.edit();
shortsleeptime = prefs.getShortSleepTime(context);
acrTransmissionRate = prefs.getAcrUploadTime(context);
vpnenable = (prefs.getVpnenable(context));
vpnenableboolean = (vpnenable != 0);
/*Reset Service Parameters ends*/
syncbutton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
/*Reset Service*/
if (DataTransLayer.canTransferData(context)){
Toast.makeText(getApplicationContext(), "Service Reset Done", Toast.LENGTH_LONG).show();
data_reset = 1;
Intent svc = new Intent(context, EngineService.class);
svc.setAction(EngineLauncher.ACTION_ALARM);
context.startService(svc);
Intent intent = new Intent(context,AppInventoryService.class);
intent.setAction(AppInventoryService.ACTION_METER_MANAGER_PUSH);
context.startService(intent);
if (eulapreferences.getBoolean(PREFERENCE_EULA_ACCEPTED, false) && Preferences.getInstance().getRegistrationStatus(context)) {
schedulealarmservice(context);
scheduleacruploadalarmservice(context, true);
}
/*Log Success Push Report*/
format = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
strName = "Sync Successful" + "," + format;
SharedPreferences preferences = context.getSharedPreferences("LOG", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("log", strName);
editor.commit();
Log.d("LOG", "Sent : " + strName);
LogListView.addItems();
/*Log Success Push Report*/
if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH && !prefs.getTunInterfaceNotAvilableStatus(context)) {
if (vpnenableboolean && !prefs.getTunInterfaceNotAvilableStatus(context)) {
String prefix = OpenVPNService.INTENT_PREFIX;
Intent stopintent = new Intent(getApplicationContext(),
OpenVPNService.class).setAction(
OpenVPNService.ACTION_DISCONNECT).putExtra(
prefix + ".STOP", true);
startService(stopintent);
defaultprefsedit.putString("currentstate", "DISCONNECTED");
defaultprefsedit.commit();
OpenVPNService.current_state = "DISCONNECTED";
prefs.setOpenVpnConfigStatus(context, true);
prefs.setVpnPopupCancelStatus(context, false);
Intent ovpnintent = new Intent(context,
OpenVpnHelperService.class);
ovpnintent
.setAction(OpenVpnServiceLauncher.ACTION_OPEN_VPN_METER_PUSH);
context.startService(ovpnintent);
}
}
}else{
Toast.makeText(getApplicationContext(), "Please check network connection", Toast.LENGTH_LONG).show();
/*Log Failed Push Report*/
format = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
strName = "Sync Failed" + "," + format;
SharedPreferences preferences = context.getSharedPreferences("LOG", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("log", strName);
editor.commit();
Log.d("LOG", "Failed : " + strName);
LogListView.addItems();
/*Log Failed Push Report*/
}
/*Reset Service ends*/
}
});
/* Titlebar + Button ends */
/* Bottom Buttons */
home = (Button) findViewById(R.id.home);
messages = (Button) findViewById(R.id.messages);
history = (Button) findViewById(R.id.history);
settings = (Button) findViewById(R.id.settings);
support = (Button) findViewById(R.id.support);
home.setBackgroundColor(Color.GRAY);
messages.setBackgroundColor(Color.GRAY);
history.setBackgroundColor(Color.GRAY);
settings.setBackgroundColor(Color.GRAY);
support.setBackgroundColor(Color.DKGRAY);
/* Bottom Buttons ends */
/*OnClick Home Button*/
home.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(Support.this, SettingsActivity.class);
Support.this.startActivity(myIntent);
}
});
/*OnClick Home Button ends*/
/* Tabs */
Bundle bundle = getIntent().getExtras();
TabHost tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;
// First Activity
intent = new Intent().setClass(this, InfoListView.class);
spec = tabHost.newTabSpec("some_things").setIndicator("Info").setContent(intent);
tabHost.addTab(spec);
// Second Activity
intent = new Intent().setClass(this, LogListView.class);
spec = tabHost.newTabSpec("top_things").setIndicator("Log").setContent(intent);
tabHost.addTab(spec);
//tabHost.getTabWidget().getChildAt(0).getLayoutParams().height = 95;
//tabHost.getTabWidget().getChildAt(1).getLayoutParams().height = 95;
/* Tabs ends */
}
/*Reset Service*/
private void schedulealarmservice(Context appcontext) {
// TODO Auto-generated method stub
Log.d("schedulealarmservice", "schedulealarmservice");
AlarmManager acrservice = (AlarmManager) appcontext
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(appcontext, AlarmServiceReceiver.class);
i.setAction(AcrServiceLauncher.ACTION_ACR_ALARM_INTENT);
PendingIntent acrpending = PendingIntent.getBroadcast(appcontext, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.add(Calendar.SECOND, (int) shortsleeptime);
acrservice.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
acrpending);
}
private void scheduleacruploadalarmservice(Context appcontext,Boolean flag) {
// TODO Auto-generated method stub
Log.d("schedulealarmservice", "scheduleacruploadalarmservice");
AlarmManager uploadservice = (AlarmManager) appcontext
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(appcontext, AlarmServiceReceiver.class);
i.setAction(AcrServiceLauncher.ACTION_ACR_UPLOAD_INTENT);
PendingIntent uploadintent = PendingIntent.getBroadcast(appcontext, 0,
i, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
if(flag){
cal.add(Calendar.SECOND, 0);
}else{
cal.add(Calendar.SECOND, acrTransmissionRate * 60);
}
uploadservice.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
uploadintent);
}
/*Reset Service Ends*/
}
答案 0 :(得分:0)
将此代码放在addItems()方法中。
SharedPreferences preferences = context.getSharedPreferences("LOG", android.content.Context.MODE_PRIVATE);
Editor editor = preferences.edit(); // you have to open shared preference in Edit mode
newString = preferences.getString("log", "");
希望它会对你有所帮助。
答案 1 :(得分:0)
您的错误可能是因为newString
为空(在SharedPreferences中找不到任何内容)所以当您调用tokens.nextToken()
时,没有任何内容,因此错误“没有这样的元素”。您确定在离开活动之前保存了偏好设置吗?您的commit()
似乎是从点击监听器调用的,可能并不总是被触发。
在任何情况下,您都需要处理newString
确实应该为空的情况。在启动tokenizer之前添加一个检查以确保。