今天解决了ListView不显示数据的问题,终于弄清楚了这个逻辑,原来根本没有把新建的信息存入数据库,把onActivityResult写在了fragment里。
遇到的问题:现在添加之后不能时时刷新ListView,尝试在Adapter中写了一个刷新的函数,调用时一直空指针错误。adapter.notifyDataSetChanged()不执行;
明天解决这一问题。
import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.Log; import android.util.SparseArray; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.RadioGroup; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import android.widget.Toolbar; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static android.view.View.GONE; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private FrameLayout fragment_container; private FragmentManager manager; private FragmentTransaction transaction; private Bundle mBundle; private Toolbar myToolbar; final String TAG = "tag"; private Context context = this; private List<Note> noteList = new ArrayList<Note>(); private NoteAdapter adapter; private PopupWindow popupWindow; // 左侧弹出菜单 private PopupWindow popupCover; // 菜单蒙版 private LayoutInflater layoutInflater; private RelativeLayout main; private ViewGroup customView; private ViewGroup coverView; private WindowManager wm; private DisplayMetrics metrics; private TagAdapter tagAdapter; private TextView setting_text; private ImageView setting_image; private ListView lv_tag; private TextView add_tag; private ShowFragment showFragment; private CycleFragment cycleFragment; private SettingFragment settingFragment; private MyFragment myFragment; private ImageView add; private int mode; private int tag; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getContentViewResource()); initView(); initData(); initList(); add = findViewById(R.id.sign_iv); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,EditActivity.class); intent.putExtra("mode",4); //新建笔记的mode设为4 startActivityForResult(intent,0); } }); //将主页添加到第一个fragment中,即默认fragment ShowFm = new ShowFragment(); getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, ShowFm).commit(); //取得用户id值 /*Intent intent = getIntent(); mIdKey = intent.getIntExtra("idKey", 0);*/ Intent intent = getIntent(); mode = intent.getIntExtra("mode",0); } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { Log.d(TAG, "onActivityResult: panduan"); int returnMode; //-1不改变 0创建一个新笔记 1修改当前笔记 long note_id;/* Bundle bundle = data.getExtras(); returnMode = bundle.getInt("mode",0);*/ returnMode = data.getExtras().getInt("mode",-1); note_id = data.getExtras().getLong("id",0); //修改笔记 if(returnMode == 1){ String content = data.getStringExtra("content"); String time = data.getStringExtra("time"); int tag = data.getExtras().getInt("tag",1); Note newNote = new Note(content,time,tag); newNote.setId(note_id); dao op = new dao(this); op.open(); op.updateNote(newNote); op.close(); //refreshListView(); } //新建笔记 else if (returnMode == 0) { Log.d(TAG, "onActivityResult: xinjianbiji"); String content = data.getExtras().getString("content"); String time = data.getExtras().getString("time"); int tag = data.getExtras().getInt("tag", 1); Note newNote = new Note(content, time, tag); dao op = new dao(this); op.open(); Log.d(TAG, "onActivityResult: tianjiadhujukujinqu"); op.addNote(newNote); op.close(); //adapter.reflesh(noteList); //refreshListView(); } //删除笔记 else if (returnMode == 2){ Note delNote = new Note(); delNote.setId(note_id); dao op = new dao(this); op.open(); op.removeNote(delNote); op.close(); } //refreshListView(); super.onActivityResult(requestCode, resultCode, data); } //private FrameLayout fragment_container; private RadioGroup rg; private Fragment ShowFm = null,CycleFm = null, SettingFm = null, MyFm = null; @Override public void onClick(View v) { } private final class RadioGroupOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener { @Override public void onCheckedChanged(RadioGroup radioGroup, int checkedId) { if (ShowFm != null) { getSupportFragmentManager().beginTransaction().hide(ShowFm).commit(); } if (CycleFm != null) { getSupportFragmentManager().beginTransaction().hide(CycleFm).commit(); } if (SettingFm != null) { getSupportFragmentManager().beginTransaction().hide(SettingFm).commit(); } if (MyFm != null) { getSupportFragmentManager().beginTransaction().hide(MyFm).commit(); } switch (checkedId) { case R.id.record_tab: if (ShowFm == null) { ShowFm = new ShowFragment(); getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, ShowFm).commit(); } else { getSupportFragmentManager().beginTransaction().show(ShowFm).commit(); } break; case R.id.cycle_tab: if (CycleFm == null) { CycleFm = new CycleFragment(); getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, CycleFm).commit(); } else { getSupportFragmentManager().beginTransaction().show(CycleFm).commit(); } break; case R.id.settings_tab: if (SettingFm == null) { SettingFm = new SettingFragment(); getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, SettingFm).commit(); } else { getSupportFragmentManager().beginTransaction().show(SettingFm).commit(); } break; case R.id.my_tab: if (MyFm == null) { MyFm = new MyFragment(); getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, MyFm).commit(); } else { getSupportFragmentManager().beginTransaction().show(MyFm).commit(); } break; } } } public int getContentViewResource() { return R.layout.activity_main; } private SparseArray<Fragment> mFragmentSparseArray; protected void initView() { fragment_container = findViewById(R.id.fragment_container); rg = findViewById(R.id.tabs_rg); } protected void initData() { } protected void initList() { rg.setOnCheckedChangeListener(new RadioGroupOnCheckedChangeListener()); rg.check(R.id.record_tab); } }
package com.example.jishibenceshi; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.SearchView; import androidx.appcompat.widget.Toolbar; import androidx.fragment.app.Fragment; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static android.view.View.GONE; import static androidx.core.os.LocaleListCompat.create; public class ShowFragment extends Fragment { /*public ShowFragment(String context){ this.context = context; }*/ private SharedPreferences deleteAll_confirm; private Passworddao mPwdDataManager; public static final String ARGUMENT = "argument"; private String mArgument; final String TAG = "tag"; //private Context context = this; private NoteDatabase dbHelper; //FloatingActionButton btn_add; private ListView lv_note; private NoteAdapter adapter; private List<Note> noteList = new ArrayList<Note>(); private Toolbar myToolbar; private PopupWindow popupWindow; // 左侧弹出菜单 private PopupWindow popupCover; // 菜单蒙版 private LayoutInflater layoutInflater; private RelativeLayout main; private ViewGroup customView; private ViewGroup coverView; private WindowManager wm; private DisplayMetrics metrics; private TagAdapter tagAdapter; private TextView setting_text; private ImageView setting_image; private ListView lv_tag; private TextView add_tag; /*public ShowFragment() { }*/ @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_show, container, false); lv_note = (ListView) view.findViewById(R.id.lv_note); myToolbar = view.findViewById(R.id.Toolbar_main); ((AppCompatActivity) getActivity()).setSupportActionBar(myToolbar); setHasOptionsMenu(true); //setSupportActionBar(myToolbar); //getSupportActionBar().setHomeButtonEnabled(true); //getSupportActionBar().setDisplayHomeAsUpEnabled(true); //用自定义的工具栏代替本身的活动栏 Bundle bundle = getArguments(); if (bundle != null) mArgument = bundle.getString(ARGUMENT); lv_note.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (parent.getId()) { case R.id.lv_note: Note curNote = (Note) parent.getItemAtPosition(position); Intent intent = new Intent(getActivity(), EditActivity.class); intent.putExtra("content", curNote.getContent()); intent.putExtra("id", curNote.getId()); intent.putExtra("time", curNote.getTime()); intent.putExtra("mode", 3); // MODE of 'click to edit' 修改笔记的mode设为3 intent.putExtra("tag", curNote.getTag()); startActivityForResult(intent, 1); //collect data from edit Log.d(TAG, "onItemClick: " + position); break; } } }); //初始化adapter adapter = new NoteAdapter(this.getActivity(), noteList); lv_note.setAdapter(adapter); refreshListView(); //return inflater.inflate(R.layout.fragment_show, container, false); return view; } public static ShowFragment newInstance(String argument) { Bundle bundle = new Bundle(); bundle.putString(ARGUMENT, argument); ShowFragment contentFragment = new ShowFragment(); contentFragment.setArguments(bundle); return contentFragment; } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { Log.d(TAG, "onActivityResult: shujukutianru"); int returnMode; //-1不改变 0创建一个新笔记 1修改当前笔记 long note_id; Bundle bundle = data.getExtras(); returnMode = bundle.getInt("mode", 0); //returnMode = data.getExtras().getInt("mode",-1); note_id = data.getExtras().getLong("id", 0); //修改笔记 if (returnMode == 1) { String content = data.getStringExtra("content"); String time = data.getStringExtra("time"); int tag = data.getExtras().getInt("tag", 1); Note newNote = new Note(content, time, tag); newNote.setId(note_id); dao op = new dao(getContext().getApplicationContext()); op.open(); op.updateNote(newNote); op.close(); //refreshListView(); } //新建笔记 else if (returnMode == 0) { Log.d(TAG, "onActivityResult: xinjianbiji"); String content = data.getExtras().getString("content"); String time = data.getExtras().getString("time"); int tag = data.getExtras().getInt("tag", 1); Note newNote = new Note(content, time, tag); dao op = new dao(getContext().getApplicationContext()); op.open(); Log.d(TAG, "onActivityResult: tianjiadhujukujinqu"); op.addNote(newNote); op.close(); } //删除笔记 else if (returnMode == 2) { Note delNote = new Note(); delNote.setId(note_id); dao op = new dao(getContext().getApplicationContext()); op.open(); op.removeNote(delNote); op.close(); } refreshListView(); super.onActivityResult(requestCode, resultCode, data); } //导航栏上的图标 @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { /*getMenuInflater().inflate(R.menu.main_menu,menu); return super.onCreateOptionsMenu(menu);*/ Log.e(TAG, "onCreateOptionsMenu()"); menu.clear(); inflater.inflate(R.menu.main_menu, menu); MenuItem mSearch = menu.findItem(R.id.action_search); SearchView mSearchView = (SearchView) mSearch.getActionView(); mSearchView.setQueryHint("Search"); mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { adapter.getFilter().filter(newText); return false; } }); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_clear: /*new AlertDialog.Builder(this.getActivity()) .setTitle("确认全部删除嘛?") .setMessage("删除全部吗?") .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Note delNote = new Note(); //delNote.setId(note_id); dao op = new dao(getContext().getApplicationContext()); op.open(); op.removeAllNote(noteList); op.close(); } *//*dbHelper = new NoteDatabase(getContext()); SQLiteDatabase db = dbHelper.getWritableDatabase(); db.delete("notes", null, null); db.execSQL("update sqlite_sequence set seq=0 where name='notes'");*//* // refreshListView(); }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create().show(); break;*/ AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("确认全部删除嘛?"); builder.setMessage("请输入密码"); View view = getLayoutInflater().inflate(R.layout.alert_password_entry, null); final EditText et_pwd = (EditText) view.findViewById(R.id.input_pwd); builder.setView(view);//设置login_layout为对话提示框 //设置正面按钮,并做事件处理 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { String input_password = et_pwd.getText().toString().trim(); //SharedPreferences.Editor editor =deleteAll_confirm.edit(); Note delNote = new Note(); //delNote.setId(note_id); dao op = new dao(getContext().getApplicationContext()); op.open(); op.removeAllNote(noteList); op.close(); Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_SHORT).show(); /*int result=mPwdDataManager.findPassword(input_password); if(result==1) { //返回1说明密码正确 //保存用户名和密码 //editor.putString("PASSWORD", input_password); Note delNote = new Note(); //delNote.setId(note_id); dao op = new dao(getContext().getApplicationContext()); op.open(); op.removeAllNote(noteList); op.close(); Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), "密码不正确", Toast.LENGTH_SHORT).show(); }*/ refreshListView(); } }); //设置反面按钮,并做事件处理 builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(getActivity(), "取消删除", Toast.LENGTH_SHORT).show(); } }); builder.show();//显示Dialog对话框 break; } return super.onOptionsItemSelected(item); } //刷新listview public void refreshListView() { Log.d(TAG, "refreshListView: "); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.getActivity()); dao op = new dao(this.getActivity()); op.open(); // set adapter if (noteList.size() > 0) noteList.clear(); noteList.addAll(op.getAllNotes()); /*if (sharedPreferences.getBoolean("reverseSort", false)) sortNotes(noteList, 2); else sortNotes(noteList, 1);*/ op.close(); adapter.notifyDataSetChanged(); } }
原创文章,作者:,如若转载,请注明出处:https://blog.ytso.com/273048.html