我正在尝试创建历史。我有两个活动。一个是用户在editText中输入值并将其存储在共享首选项中,另一个用于使用共享首选项以列表视图形式显示值。我不知道错误是什么,因为应用程序崩溃了。
第一项活动
package com.example.sy.list;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
public class History extends AppCompatActivity {
Button translate;
Button next;
EditText enterText;
private SharedPreferences hPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
enterText = findViewById(R.id.editText);
next = findViewById(R.id.btnNext);
translate = findViewById(R.id.buttonTranslate);
View.OnClickListener addlistener = new View.OnClickListener() {
@Override
public void onClick(View view) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(enterText.getWindowToken(), 0);
hPreferences = getSharedPreferences("SaveHistory",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = hPreferences.edit();
editor.putString("history",enterText.getText().toString());
editor.apply();
enterText.setText("");
}
};
translate.setOnClickListener(addlistener);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(History.this,MainActivity.class);
startActivity(intent);
}
});
}
}
第二项活动
package com.example.sy.list;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> itemList = new ArrayList<String>();
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, itemList);
listView.setAdapter(adapter);
listView = findViewById(R.id.listView);
SharedPreferences transHistory = getSharedPreferences("SaveHistory",Context.MODE_PRIVATE);
String tHistory = transHistory.getString("history","Data Not Found");
itemList.add(tHistory);
adapter.notifyDataSetChanged();
}
}
答案 0 :(得分:0)
你错误的原因可能是:
listView.setAdapter(适配器);
listView = findViewById(R.id.listView);
首先,您设置了适配器listView.setAdapter(adapter);
但问题是,因为您调用了listView
listView = findViewByIt(R.id.listview);
不为空
所以,切换语句,你应该好好去
修改强>
listView = findViewById(R.id.listView);
然后
listView.setAdapter(adapter);