当我点击ListView item时如何关闭AlertDialog?

下面是 dialog 代码,在 dialog 中有一个 ListView,我想在点击 ListView item 时关闭AlertDialog:

public void createSearchDialog(final String[] Memo){
        LayoutInflater factory = LayoutInflater.from(this);
        View searchView = factory.inflate(R.layout.seach_dialog, null);

            lv = (ListView) searchView.findViewById(R.id.search_list);
        lv.setAdapter(new MyPerformanceArrayAdapter(this, Memo, memo_PW));
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View view, int position,long arg3) {
                // TODO Auto-generated method stub

                         /// close dialog
            }
        });
        searchBuilder = new AlertDialog.Builder(this);
        searchBuilder.setTitle("Search")
               .setView(searchView)
               .setNegativeButton("Back", new DialogInterface.OnClickListener() {               
                public void onClick(DialogInterface arg0, int arg1) {
                    // TODO Auto-generated method stub

                }
            })
               .show();     
    }

我想在onItemClick()方法中加入代码

但是不能执行。
怎么处理?

baimy1985
balmy 为什么不能执行?有什么异常?
6 年多之前 回复

2个回答

private void windowDialog(){
      Window mWindow = newDialogView();
      mWindow.setContentView(R.layout.kl_dialog_invite_code);
      ListView listview=mWindow.findViewById(R.id.xxx);
      //在onItemClick事件中调用mDialog.dismiss();就ok了
}

private Window newDialogView() {
        if (mDialog == null) {
            mDialog = new Dialog(this, R.style.mydialog);
            mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        mDialog.show();
        mDialog.setCanceledOnTouchOutside(true);
        mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
        Window win = mDialog.getWindow();
        WindowManager.LayoutParams lp = win.getAttributes();
        // lp.alpha = 0.9f;
        win.setAttributes(lp);
        // WindowManager.LayoutParams.FLAG_DIM_BEHIND 背景渐变
        // WindowManager.LayoutParams.FLAG_BLUR_BEHIND 背景模糊
        win.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        return win;
}
searchBuilder.dismiss().

是这个关闭吗

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
求指导!BaseAdapter监听的ListView如何设置长点击删除item
希望长点击一个item后会弹出AlertDialog,确定的话就会删除该ListView的item, 监听器是BaseAdapter
关于 AlertDialog PositiveButton 和 NegativeButton 的问题
我使用下面的代码在AlertDialog中显示文件夹列表: ListDialog = new AlertDialog.Builder(MyActivity.this); ListDialog.setTitle("Folder List"); ListView folder = new ListView(MyActivity.this); //scan folder folder.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View v, int position, long id) { //scan sub-folder }); ListDialog.setPositiveButton("Save", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { //do something } }); ListDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { //back } }); 我想让 AlertDialog的 NegativeButton 总是显示,而当 list item 数是0时, AlertDialog的 PositiveButton 才显示。如何实现?
小白求教 android中listview的点击冲突问题
刚才写了一段代码 想通过点击listview上每一项的imageview删除数据库中对应的这一条数据, 但运行时每次都必须点击两下imageview才能删除这一项,之前想过在listview的适配器中来做这个 操作,但是看过的代码好像都没有这么做过并且这样做的话没法更新数据,现在想问问 有没有什么好的方法可以解决这个问题 。对了,设置focusable和clickable属性也没法处理。设置成imagebutton的话 , 由于listview的每一项是通过反射来获取到的 给imagebutton设置onclick属性的话 ,数据就没法传递了,毕竟还是要删除数据库中的数据 ```package com.personal.fyd.blacknumber; import android.content.Context; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import java.util.List; /** * Created by asus on 2016/10/19. */ public class MyAdapter extends BaseAdapter { private List<NumberBean> list; private Context context; public MyAdapter(List<NumberBean> list, Context context) { this.list = list; this.context = context; // for (NumberBean bean:list // ) { // Log.i(context+"",bean.getNumber()+" "+bean.getMode()); // } } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; NumberBean bean; if (convertView == null) { convertView = View.inflate(context, R.layout.item, null); viewHolder = new ViewHolder(); viewHolder.number_tv = (TextView) convertView.findViewById(R.id.tv_number); viewHolder.mode_tv = (TextView) convertView.findViewById(R.id.tv_mode); viewHolder.delete_iv = (ImageView) convertView.findViewById(R.id.iv_delete); convertView.setTag(viewHolder); }else { viewHolder = (ViewHolder) convertView.getTag(); } bean = list.get(position); viewHolder.number_tv.setText(bean.getNumber()); String mode = bean.getMode(); if ("1".equals(mode)){ viewHolder.mode_tv.setText("电话拦截"); }else if ("2".equals(mode)){ viewHolder.mode_tv.setText("短信拦截"); }else if ("3".equals(mode)){ viewHolder.mode_tv.setText("全部拦截"); } return convertView; } static class ViewHolder { TextView number_tv; TextView mode_tv; ImageView delete_iv; } } ``` package com.personal.fyd.blacknumber; import android.content.Context; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.Toast; import java.util.List; public class MainActivity extends AppCompatActivity { private final Context context = MainActivity.this; private ListView lv; private AlertDialog alertDialog; private NumberDao numberdao; private MyAdapter adapter; private List<NumberBean> list; private ImageView iv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); updateLV(); } private void updateLV() { list = numberdao.findAll(); adapter = new MyAdapter(list,MainActivity.this); lv.setAdapter(adapter); } private void initView() { lv = (ListView) findViewById(R.id.lv); numberdao = new NumberDao(this); iv = (ImageView) findViewById(R.id.iv_delete); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, final int position, long id) { Toast.makeText(context,"再次点击删除此项",Toast.LENGTH_SHORT).show(); view.findViewById(R.id.iv_delete).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String num = list.get(position).getNumber(); // Toast.makeText(context,num,Toast.LENGTH_SHORT).show(); numberdao.delete(num); numberdao.findAll(); updateLV(); } }); } }); } public void delete(View view){ } public void add(View view){ showDiagle(); } //显示对话框 private void showDiagle(){ AlertDialog.Builder builder = new AlertDialog.Builder(this); View view = View.inflate(this,R.layout.diagle,null); builder.setView(view); final EditText editText = (EditText) view.findViewById(R.id.blacknumber_et); final CheckBox call_cb = (CheckBox) view.findViewById(R.id.call_cb); final CheckBox sms_cb = (CheckBox) view.findViewById(R.id.sms_cb); Button commit = (Button) view.findViewById(R.id.commit_btn); Button cancel = (Button)view.findViewById(R.id.cancel_btn); commit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String number = editText.getText().toString(); //判断是否为空 if (TextUtils.isEmpty(number)){ Toast.makeText(MainActivity.this,"number ",Toast.LENGTH_SHORT).show(); return; } String mode; if (call_cb.isChecked()&&sms_cb.isChecked()){ mode = "3"; }else if (call_cb.isChecked()){ mode = "1"; }else if (sms_cb.isChecked()){ mode = "2"; }else { Toast.makeText(MainActivity.this,"请至少选择一种拦截方式",Toast.LENGTH_SHORT).show(); return; } //操作合法 插入数据 numberdao.insert(number,mode); //插入成功 重新查询 alertDialog.dismiss(); updateLV(); } }); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); } }); alertDialog = builder.create(); alertDialog.show(); } } ``` ```
listview 如何删除sdcard卡文件并刷新界面?红色部分
package com.genny; import java.io.File; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.view.ContextMenu; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.CursorAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.SimpleAdapter; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.*; public class MusicListActivity extends Activity{ private ListView listview; private Cursor c = null; private File file = null; private CursorAdapter adapter; private ScanSdReceiver scanSdReceiver = null; private String[] _title = null; private String[] _name = null; private String[] _size; private String[] _path = null; private String[] _singer = null; private String[] _album = null; private int[] _time; private int index; //menu菜单 private static final int ITEM1 = Menu.FIRST; private static final int ITEM2 = Menu.FIRST + 1; private static final int ITEM3 = Menu.FIRST + 2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.musiclist); listview = (ListView)findViewById(android.R.id.list); c = this.getContentResolver() .query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Audio.Media.TITLE,//歌曲名0 MediaStore.Audio.Media.DURATION,//时长1 MediaStore.Audio.Media.ARTIST,//歌手2 MediaStore.Audio.Media._ID,//ID3 MediaStore.Audio.Media.DISPLAY_NAME,//文件名4 MediaStore.Audio.Media.ALBUM,//专辑5 MediaStore.Audio.Media.SIZE,//大小6 MediaStore.Audio.Media.DATA},//路径7 null, null, null); /* if (c==null || c.getCount()==0){ builder = new AlertDialog.Builder(this); builder.setMessage("存储列表为空...").setPositiveButton("确定", null); ad = builder.create(); ad.show(); }*/ c.moveToFirst(); _title = new String[c.getCount()]; _name = new String[c.getCount()]; _path = new String[c.getCount()]; _singer = new String[c.getCount()]; _album = new String[c.getCount()]; _size = new String[c.getCount()]; _time = new int[c.getCount()]; for(int i=0;i<c.getCount();i++){ _title[i] = c.getString(0); _name[i] = c.getString(4); _path[i] = c.getString(7); _singer[i] = c.getString(2); _album[i] = c.getString(5); _size[i] = c.getString(6); _time[i] = c.getInt(1); c.moveToNext(); } adapter = new SimpleCursorAdapter(this, R.layout.listitem, c, new String[]{MediaStore.Audio.AudioColumns.TITLE, MediaStore.Audio.AudioColumns.ARTIST}, new int[]{R.id.music, R.id.songer}); listview.setAdapter(adapter); listview.setOnItemClickListener(new ListItemClickListener()); registerForContextMenu(listview); } class ListItemClickListener implements OnItemClickListener{ @Override public void onItemClick(AdapterView<?> arg0, View view, int position, long id) { // TODO Auto-generated method stub Intent i = new Intent(MusicPlayerService.MUSIC_CONTROL); i.putExtra("cmd", MusicPlayerService.CMD_JUMP); i.putExtra("pos", position); sendBroadcast(i); finish(); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { // TODO Auto-generated method stub index = ((AdapterContextMenuInfo)menuInfo).position;//获取menu点击项的position menu.setHeaderIcon(R.drawable.header_icon); menu.setHeaderTitle(_title[index]); menu.add(0,ITEM1,0,"播放"); menu.add(0,ITEM2,0,"删除"); menu.add(0,ITEM3,0,"详细"); super.onCreateContextMenu(menu, v, menuInfo); } public boolean onContextItemSelected(MenuItem item){ switch(item.getItemId()){ case ITEM1: Intent i = new Intent(MusicPlayerService.MUSIC_CONTROL); i.putExtra("cmd", MusicPlayerService.CMD_JUMP); i.putExtra("pos", index); sendBroadcast(i); finish(); break; [color=red]case ITEM2: /*下面的代码能够删除listview中的音频文件,但是删除之后如何刷新呢?*/ file = new File(_path[index]); if(file.exists()){ file.delete(); } break;[/color] case ITEM3: Intent intent = new Intent(MusicListActivity.this,MusicInfo.class); intent.putExtra("_Name", _name[index]); intent.putExtra("_Size", _size[index]); intent.putExtra("_Singer", _singer[index]); intent.putExtra("_Album", _album[index]); intent.putExtra("_Time", _time[index]); intent.putExtra("_Path", _path[index]); startActivity(intent); System.out.println("Name:"+_name[index]+" Size:"+_size[index]+" Path:"+_path[index]+" Singer:"+_singer[index]+" Album:"+_album[index]+" Time:"+_time[index]); break; default: break; } return super.onContextItemSelected(item); } //添加menu菜单 public boolean onCreateOptionsMenu(Menu menu){ super.onCreateOptionsMenu(menu); menu.add(0,ITEM1,0,"更新列表").setIcon(R.drawable.update_file); menu.add(0,ITEM2,0,"返回").setIcon(R.drawable.menu_exit); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case ITEM1: scanSdCard(); break; case ITEM2: onBackPressed(); break; default: break; } return true; } //扫描本地sdcard卡文件 private void scanSdCard(){ IntentFilter intentfilter = new IntentFilter(Intent.ACTION_MEDIA_SCANNER_STARTED); intentfilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); intentfilter.addDataScheme("file"); scanSdReceiver = new ScanSdReceiver(); registerReceiver(scanSdReceiver, intentfilter); sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://"+Environment.getExternalStorageDirectory().getAbsolutePath()))); } @Override public void onBackPressed() { // TODO Auto-generated method stub if (scanSdReceiver!=null) unregisterReceiver(scanSdReceiver); this.finish(); super.onBackPressed(); } }
ListView中因layout_height是wrap_content而引发的问题
问题描述: 先是点击画面上的一个按钮,然后出现下方弹窗 图一:点击弹窗内的“show preview”,会出现listview,如图二 ![图一:点击弹窗内的“show preview”,会出现listview,如图二](https://img-ask.csdn.net/upload/201806/04/1528124307_944119.png) 图二:listview出现之后,快速点击任意item,按照设计应该是出现图一的画面 ![图二:listview出现之后,快速点击任意item,按照设计应该是出现图一的画面](https://img-ask.csdn.net/upload/201806/04/1528124418_35363.png) 但是实际上出现的是图三的画面, 图三:图中出现了和listview大小一样的透明层 ![图三:图中出现了和listview大小一样的透明层](https://img-ask.csdn.net/upload/201806/04/1528124620_124752.png) 这种现象只会在listview初始化的时候并且是快速点击下才会出现,往后怎么点击都不会出现。 现在怀疑这个问题可能是因为ListView中的layout_height是wrap_content而引发的问题,改成具体fill_parem或者是具体的高度就能够解决,但是要怎么证明这个现象是由这个问题导致的呢? 代码如下: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/flipper_setting" android:layout_width="fill_parent" android:layout_height="400px" android:orientation="vertical" android:gravity="center_vertical" android:background="@color/gold" > <!-- setting category page --> <LinearLayout android:id="@+id/layout1" android:layout_width="fill_parent" android:layout_height="400px" android:gravity="top" android:orientation="vertical"> <!-- Preview Setting --> <include android:id="@+id/include_setting_preview" layout="@layout/list_row_setting_category" /> </LinearLayout> <!-- detail setting page --> <LinearLayout android:layout_width="fill_parent" android:layout_height="400px" android:gravity="top" android:orientation="vertical" android:id="@+id/layout2"> <TextView android:id="@+id/text_title_detail" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:textSize = "20px"/> <com.example.viewflippertest.ListViewConfig android:id="@+id/listview_detail" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@color/white" /> </LinearLayout> </LinearLayout> ``` ``` public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.id_btn) ; button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Dialog dialog = createOtherSettingDialog(MainActivity.this); dialog.show(); WindowManager.LayoutParams lp = dialog.getWindow().getAttributes(); lp.width = 600; lp.height = 500; dialog.getWindow().setAttributes(lp); } }); } public static AlertDialog createOtherSettingDialog(final Context context) { //(1) LayoutInflater inflater = LayoutInflater.from(context); final View view = inflater.inflate(R.layout.dlg_setting_other, null); final ListViewConfig listView_detail = (ListViewConfig)view.findViewById(R.id.listview_detail); final TextView text_detail_title = (TextView)view.findViewById(R.id.text_title_detail); final LinearLayout layout2 = (LinearLayout) view.findViewById(R.id.layout2); final LinearLayout layout1 = (LinearLayout) view.findViewById(R.id.layout1); layout2.setVisibility(View.GONE); //(2) /*============ Preview Setting ================*/ final LinearLayout layout_preview = (LinearLayout)view.findViewById(R.id.include_setting_preview); final ArrayAdapter<String> adapter_preview = new adaper(context, R.layout.list_row_setting_detail, R.id.text_detail); final TextView text_category_preview = (TextView)layout_preview.findViewById(R.id.text_category); final TextView text_value_preview = (TextView)layout_preview.findViewById(R.id.text_value); text_category_preview.setText(context.getString(R.string.txid_scan_b_other_preview_title)); text_value_preview.setText("On"); final List<String> list_preview = new ArrayList<String>(); list_preview.add(0, "On"); list_preview.add(1, "Off"); for(int i=0; i<list_preview.size(); ++i) { adapter_preview.add(list_preview.get(i)); } layout_preview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { System.out.println("========= layout_preview onclick"); text_detail_title.setText(R.string.txid_scan_b_other_preview_title); listView_detail.setAdapter(adapter_preview); layout1.setVisibility(View.GONE); layout2.setVisibility(View.VISIBLE); } }); /*===============================================*/ //(3) listView_detail.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { System.out.println("========= listView_detail onclick"); if(parent.getAdapter().equals(adapter_preview)) { // Update preview setting String value = adapter_preview.getItem(position); TextView text_value = (TextView)layout_preview.findViewById(R.id.text_value); text_value.setText(value); } else { /* should never reach this point */ } layout1.setVisibility(View.VISIBLE); layout2.setVisibility(View.GONE); } }); //(4) final AlertDialog.Builder dialog = new AlertDialog.Builder(context); dialog.setTitle(context.getString(R.string.txid_scan_t_top_other_title)); dialog.setNegativeButton(context.getString(R.string.txid_cmn_b_close), null); dialog.setView(view); return dialog.create(); } private static class adaper extends ArrayAdapter<String>{ public adaper(Context context, int resource, int textViewResourceId) { super(context, resource, textViewResourceId); // TODO Auto-generated constructor stub } @Override public View getView(int position, View convertView, ViewGroup parent) { System.out.println("========= position:" + position + ",convertView:" + convertView +",parent:" + parent.getMeasuredHeight() +",parent.getChildCount:" + parent.getChildCount()); return super.getView(position, convertView, parent); } } ```
android listview添加出现问题
我是一枚新手,在写添加listview并对数据库进行增删改查时遇到了问题,添加listview时我想添加一个item可是一添加就添加了好多行,还有插入数据后不能listview没有显示之前插入的值,求大神给看看!这是我的代码: ``` public class DLXMainActivity extends AppCompatActivity { private Toolbar mToolbar; public static EditText mDlxInput1, mDlxInput2;//输入框 public TextView mTitle, mContent, mTime;//显示内容 DatabaseHelper mDatabaseHelper = new DatabaseHelper(this); static List<Comment> mList = new ArrayList<>(); static Comment mComment = new Comment(); MyAdapter mAdapter; ListView mListView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dlx_task3_dlxmain); initViewValue(); } public void initViewValue() { findViews(); setSupportActionBar(mToolbar); setOnclicklistener(); } //数据库的初始化和按下删除的监听事件 public void setOnclicklistener() { mDatabaseHelper = new DatabaseHelper(this); mAdapter = new MyAdapter(this, mList); mListView.setAdapter(mAdapter); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mComment = mList.get(position); int positioncurrent = mComment.getId(); mDatabaseHelper.databaseDelete(positioncurrent); mList.remove(mComment); mAdapter.notifyDataSetChanged(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.dlx_task3_menu, menu); return super.onCreateOptionsMenu(menu); } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_add: showDialog_Layout(DLXMainActivity.this); break; } return super.onOptionsItemSelected(item); } //对话框 private void showDialog_Layout(final Context context) { LayoutInflater inflater = LayoutInflater.from(this); final View textEntryView = inflater.inflate(R.layout.dlx_task3_dialoglayout, null); final AlertDialog.Builder builder = new AlertDialog.Builder(context); mDlxInput1 = (EditText) textEntryView.findViewById(R.id.dlx_Input1); mDlxInput2 = (EditText) textEntryView.findViewById(R.id.dlx_Input2); builder.setCancelable(false); builder.setTitle(R.string.dlx_add); builder.setView(textEntryView); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { setTitle(""); } }); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mDatabaseHelper.databaseInsert(); mDatabaseHelper.databaseFind(context); mAdapter.notifyDataSetChanged(); } }); builder.show(); } public void findViews() { mToolbar = (Toolbar) findViewById(R.id.toolbar); mTitle = (TextView) findViewById(R.id.dlx_maintitle); mContent = (TextView) findViewById(R.id.dlx_maincontent); mTime = (TextView) findViewById(R.id.dlx_maintime); mListView = (ListView) findViewById(R.id.dlx_lv); } } public class MyAdapter extends BaseAdapter { public List<Comment> list; public LayoutInflater mInflater = null; Context context; DatabaseHelper mDatabaseHelper = new DatabaseHelper(context); public MyAdapter(Context context, List<Comment> list) { this.mInflater = LayoutInflater.from(context); this.context = context; this.list = list; } //ViewHolder静态类 static class ViewHolder { public TextView title; public TextView content; public TextView time; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } //获取一个在数据集中指定索引的视图来显示数据 public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder = null; //如果缓存convertView为空,则需要创建View if (convertView == null) { holder = new ViewHolder(); //根据自定义的Item布局加载布局 convertView = mInflater.inflate(R.layout.dlx_task3_commentlayout, null); holder.title = (TextView) convertView.findViewById(R.id.dlx_maintitle); holder.content = (TextView) convertView.findViewById(R.id.dlx_maincontent); holder.time = (TextView) convertView.findViewById(R.id.dlx_maintime); //将设置好的布局保存到缓存中,并将其设置在Tag里,以便后面方便取出Tag convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.title.setText(list.get(position).getTitle()); holder.content.setText(list.get(position).getContent()); holder.time.setText(mDatabaseHelper.getTimeShow(context, (list.get(position).getTime()))); return convertView; } } public class DatabaseHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "Comment.db"; public static final String TABLE_NAME = " comment"; public long mDatetimecurrent; Context context; public long mDatetime; // TODO: 2016/5/18 public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE" + TABLE_NAME + "(" + Comment.Commentinter.EVENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Comment.Commentinter.EVENT_TITLE + " TEXT NOT NULL, " + Comment.Commentinter.EVENT_CONTENT + " TEXT NOT NULL, " + Comment.Commentinter.EVENT_TIME + " INTEGER NOT NULL);"); } public void databaseInsert() { SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); mDatetime = System.currentTimeMillis(); //开始组装第一条数据 values.put("title", String.valueOf(DLXMainActivity.mDlxInput1.getText())); values.put("content", String.valueOf(DLXMainActivity.mDlxInput2.getText())); values.put("time", mDatetime); db.insert(TABLE_NAME, null, values);//插入第一条数据 db.close(); } /** * 删除数据库元素 * * @param */ public void databaseDelete(int positioncurrent) { SQLiteDatabase db = getWritableDatabase(); String[] args = {String.valueOf(positioncurrent)}; db.delete("comment", Comment.Commentinter.EVENT_ID + "=?", args); db.close(); } /** * 从数据库中取值并放到listview中 * @param context */ public void databaseFind(Context context) { this.context = context; SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.query(DatabaseHelper.TABLE_NAME,new String[] {Comment.Commentinter.EVENT_ID, Comment.Commentinter.EVENT_TITLE, Comment.Commentinter.EVENT_CONTENT,Comment.Commentinter.EVENT_TIME}, null, null, null, null, null, null); //DLXMainActivity.mList.clear(); while (cursor.moveToNext()) { String title = cursor.getString(cursor.getColumnIndex(Comment.Commentinter.EVENT_TITLE)); String content = cursor.getString(cursor.getColumnIndex(Comment.Commentinter.EVENT_CONTENT)); long time = cursor.getLong(cursor.getColumnIndex(Comment.Commentinter.EVENT_TIME)); int id = cursor.getInt(cursor.getColumnIndex(Comment.Commentinter.EVENT_ID)); DLXMainActivity.mComment.setTitle(title); DLXMainActivity.mComment.setContent(content); DLXMainActivity.mComment.setTime(time); DLXMainActivity.mComment.setId(id); DLXMainActivity.mList.add(DLXMainActivity.mComment); } cursor.close(); db.close(); } public String getTimeShow(Context context, long datetime) { mDatetimecurrent = System.currentTimeMillis(); long time = mDatetimecurrent - datetime; if (time / 1000 != 0) { if (time / 60000 != 0) { if (time / 3600000 != 0) { if (time / 86400000 != 0) { return time / 86400000 + context.getString(R.string.dlx_day1); } else { return time / 3600000 + context.getString(R.string.dlx_hour); } } else { return time / 60000 + context.getString(R.string.dlx_minute); } } else { return time / 1000 + context.getString(R.string.dlx_second); } } else { return context.getString(R.string.dlx_gang); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { onCreate(db); } @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); } ```
android listview适配器的错误
具体报错见下面。高手求解决····· 先贴代码,下面是PointMgrActivity.java package com.app.bluetoothpro; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.app.DB.DBManager; import com.app.DB.PointClass; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.SimpleAdapter; public class PointMgrActivity extends Activity { protected static final String ACTIVITY_TAG = "LogDemo"; private DBManager dbManager; public SQLiteDatabase db; String gID; String pStatu; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.point_mgr); dbManager = new DBManager(this); /* * Points person = new Points(); person.pid = "id1"; person.pstatu = * "OFF"; db.execSQL("INSERT INTO points VALUES (?, ?)", new * Object[]{person.pid, person.pstatu}); */ addbtn(); } /********************************* 添加add方法 ****************************************/ public void add() { ArrayList<PointClass> persons = new ArrayList<PointClass>(); PointClass person = new PointClass(gID, pStatu); persons.add(person); dbManager.add(persons); } * */***************************** 添加query()查询方法 ******************************/ public void query() { List<PointClass> persons = dbManager.query(); ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>(); for (PointClass person : persons) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("pid", person.pid); map.put("pstatu", getstatu(pStatu)); listItem.add(map); Log.d(ACTIVITY_TAG, person.pid + " +++++++++++++++++++++++++++ " + getstatu(pStatu)); } ListView list = (ListView) findViewById(R.id.pointListView); SimpleAdapter listItemAdapter = new SimpleAdapter(this, listItem, R.layout.point_mgr_list_item, new String[] { "pointsID", "pointsStatu" }, new int[] { R.id.pointsID, R.id.pointsStatu }); list.setAdapter(listItemAdapter); list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub } }); } private Object getstatu(String str) { // TODO Auto-generated method stub if (str.equals("ON")) { return R.drawable.led_green; } else { return R.drawable.led_red; } }* * /************************* 为添加按钮添加事件 **************************/ void addbtn() { ImageButton ib_add = (ImageButton) findViewById(R.id.addpoint); ib_add.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { LayoutInflater inflater = getLayoutInflater(); final View layout = inflater.inflate(R.layout.add_dialog, (ViewGroup) findViewById(R.id.dialog)); new AlertDialog.Builder(PointMgrActivity.this) .setTitle("请添加节点") .setView(layout) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { EditText et = (EditText) layout .findViewById(R.id.addID); gID = et.getText().toString(); pStatu = "OFF"; /***************************************** 将输入的id,状态写入map中 **************/ Log.i(PointMgrActivity.ACTIVITY_TAG, gID + " " + pStatu); // insert(db,gID,pStatu); // close(db); add(); query(); /******************** 调试代码 ********************************************/ Log.i(PointMgrActivity.ACTIVITY_TAG, gID); /***************************************************************************************/ } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); } }); } } layout.xml布局文件中有listview,有 两列textview imageview , 上面query()方法是将从sqlite查询的数据在listview显示,下面是适配器代码: ListView list = (ListView) findViewById(R.id.pointListView); SimpleAdapter listItemAdapter = new SimpleAdapter(this, listItem, R.layout.point_mgr_list_item, new String[] { "pointsID", "pointsStatu" }, new int[] { R.id.pointsID, R.id.pointsStatu }); list.setAdapter(listItemAdapter); log调试得到正确从数据库查询数据,就是不listview显示数据. 运行报错: 10-23 10:56:36.670: E/BitmapFactory(12701): Unable to decode stream: java.io.FileNotFoundException: /: open failed: EISDIR (Is a directory)
Android 对话框中在黑色的背景上的黑色文字
我想在对话框中设置一个ListView中背景为白色,文本为黑色。下面的代码生成一个对话框,是一个黑色的背景带有黑色的字体。但是contextmenu看起来是正确的,有白色背景和黑色字体。 我把主题设置为Light,还要添加什么呢? dialog1 = new Dialog(this); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select Color Mode"); ListView modeList = new ListView(this); String[] stringArray = new String[] { "Bright Mode", "Normal Mode" }; ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, stringArray); modeList.setAdapter(modeAdapter);
使用shared preferences如何删除list item?
我有下面的adapter自定义类,创建了listview和items,但是我想在点击reset按钮时,从list中删除所有的items。 public class Scores extends Activity implements OnClickListener { public static final String MY_PREFS_NAME = "PrefName"; SharedPreferences pref; static String[] tempTime = new String[10]; static String[] tempScore = new String[10]; private static class EfficientAdapter extends BaseAdapter { private LayoutInflater mInflater; public EfficientAdapter(Context context) { mInflater = LayoutInflater.from(context); } public int getCount() { return tempTime.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate( R.layout.mathmatch_score_format, null); holder = new ViewHolder(); holder.text1 = (TextView) convertView .findViewById(R.id.time_text); holder.text2 = (TextView) convertView .findViewById(R.id.score_text); /*final ImageView deleteButton = (ImageView) convertView.findViewById(R.id.score_reset); deleteButton.setOnClickListener(this);*/ convertView.setTag(holder); //deleteButton.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.text1.setText(tempTime[position]); holder.text2.setText(tempScore[position]); return convertView; } static class ViewHolder { TextView text1; TextView text2; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mathmatch_score); setUpViews(); pref = getSharedPreferences(MY_PREFS_NAME, 0); strTime = pref.getString("high_score_times", ""); intScore = pref.getString("high_score_values", ""); tempTime = strTime.split(","); tempScore = intScore.split(","); Comparator<String> comparator = new CustomArrayComparator<String, String>(tempScore, tempTime); Arrays.sort(tempTime, comparator); Arrays.sort(tempScore, Collections.reverseOrder()); lv.setAdapter(new EfficientAdapter(this)); } private void setUpViews() { lv = (ListView) findViewById(R.id.list); reset = (ImageView) findViewById(R.id.score_reset); reset.setOnClickListener(this); } @Override protected void onPause() { super.onPause(); pref = getSharedPreferences(MY_PREFS_NAME, 0); SharedPreferences.Editor edit = pref.edit(); edit.putString("high_score_times", strTime); edit.putString("high_score_values", intScore); edit.commit(); } @Override protected void onStop() { super.onStop(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.score_reset: AlertDialog.Builder alertbox = new AlertDialog.Builder(this); alertbox.setTitle("Reset"); alertbox.setMessage("Are you sure all time ans score are reset?"); alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { pref = getSharedPreferences(MY_PREFS_NAME, 0); SharedPreferences.Editor edit = pref.edit(); /*edit.remove("high_score_times"); edit.remove("high_score_values");*/ /*edit.remove(intScore); edit.remove(strTime); */ //edit.clear(); edit.remove(MY_PREFS_NAME); edit.commit(); } }); alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { Toast.makeText(getApplicationContext(), "'No' button clicked", Toast.LENGTH_SHORT).show(); } }); alertbox.show(); break; default: break; }}} Reset按钮不在list中。上面的代码是点击yes按钮事件,但是没有任何更新。如何改正这个问题呢?
自学Android开发 在模拟器运行闪退
初学者自写的程序 ,但是在模拟器下运行闪退!!该怎么改呀?? package com.example.work3; import java.util.ArrayList; import java.util.List; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.TabActivity; import android.content.DialogInterface; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.StrictMode; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Spinner; import android.widget.TabHost; import android.widget.TextView; import android.os.Build; public class MainActivity extends TabActivity { private TabHost tabhost; private ListView listview; private ArrayAdapter<String> arr_adapter; private Spinner spinner; private List<String>list; private ArrayAdapter<String> adapter; private EditText et1,et2; private Button bt; String name; String value; String style; @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); et1=(EditText) findViewById(R.id.editText1); et2=(EditText) findViewById(R.id.editText2); bt=(Button) findViewById(R.id.button1); setContentView(R.layout.activity_main); tabhost=getTabHost(); tabhost.addTab(tabhost.newTabSpec("菜单一").setIndicator("首页").setContent(R.id.tab1)); tabhost.addTab(tabhost.newTabSpec("菜单二").setIndicator("新增").setContent(R.id.tab2)); tabhost.addTab(tabhost.newTabSpec("菜单三").setIndicator("账单").setContent(R.id.tab3)); //按钮监听 提取信息 bt.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub name = et1.getText().toString(); value = et2.getText().toString(); style = spinner.getSelectedItem().toString(); } }); listview = (ListView) findViewById(R.id.listview); //新建适配器 String[]arr_data={"数据1","数据2","数据3","数据4","数据5"}; //ArrayAdapter(上下文,当前ListView加载的每一个列表项所对应的布局文件,数据源) arr_adapter =new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,arr_data); listview.setAdapter(arr_adapter); spinner=(Spinner) findViewById(R.id.spinner); //数据源 String[]list = {"1.日常食品支出","2.人情世故支出","3.出差旅游支出","4.服饰鞋帽支出","5.生活用品支出","6.其他支出"}; //新建适配器 adapter=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list); //设置下拉样式 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //加载适配器 spinner.setAdapter(adapter); } //退出对话框 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK ) { // 创建退出对话框 AlertDialog isExit = new AlertDialog.Builder(this).create(); // 设置对话框标题 isExit.setTitle("系统提示"); // 设置对话框消息 isExit.setMessage("确定要退出吗"); // 添加选择按钮并注册监听 isExit.setButton("确定", listener); isExit.setButton2("取消", listener); // 显示对话框 isExit.show(); } return false; } /**监听对话框里面的button点击事件*/ DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { switch (which) { case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序 finish(); break; case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框 break; default: break; } } }; }
AsyncTask中的 PostExecute() 不能加载
我执行了下面的代码: package com.crumbin.tabs; //java package import java.io.IOException; import java.util.ArrayList; import org.json.JSONException; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Bundle; import android.widget.ListView; import com.crumbin.main.R; import com.crumbin.models.User; import com.crumbin.utilities.UserFollowingListAdapter; public class HomeActivity extends Activity{ final ArrayList<User> users1 = new ArrayList<User>(); User user; // public ArrayList<User> users1 = new ArrayList<User>(); private UserFollowingListAdapter csl; private ListView lv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.user_main_tab_home); lv = (ListView) findViewById(R.id.user_crumbs_list); // ListView lv = (ListView) findViewById(R.id.user_crumbs_list); AsyncLoader task = new AsyncLoader(); task.execute(); } private class AsyncLoader extends AsyncTask<String,Void, String> { ProgressDialog dialog; @Override protected void onPreExecute(){ String pa = "helllo"; return; } @Override protected String doInBackground(String... pa) { String response = ""; try { try { user = new User("4eeb34c6d80e8f1214000000"); user.getFollowingCrumbsUpList(); for(User u : user.following){ users1.add(u); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } return response; } protected void onPostExecute(String result) { //dialog.dismiss(); ListView lv = (ListView) findViewById(R.id.user_crumbs_list); final UserFollowingListAdapter csl = new UserFollowingListAdapter(HomeActivity.this,R.layout.user_crumbs_list_item,users1,this); lv.setAdapter(csl); return; } } void showError(){ new AlertDialog.Builder(this) .setTitle(" Oops , Server down :( ") .setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { // TODO Auto-generated method stub } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Do nothing. } }).show(); } } Error: 01-22 13:11:34.596: E/AndroidRuntime(2464): FATAL EXCEPTION: main 01-22 13:11:34.596: E/AndroidRuntime(2464): java.lang.ClassCastException: com.crumbin.tabs.HomeActivity$AsyncLoader cannot be cast to android.app.Activity 01-22 13:11:34.596: E/AndroidRuntime(2464): at com.crumbin.utilities.UserFollowingListAdapter.<init>(UserFollowingListAdapter.java:40) 01-22 13:11:34.596: E/AndroidRuntime(2464): at com.crumbin.tabs.HomeActivity$AsyncLoader.onPostExecute(HomeActivity.java:106) 01-22 13:11:34.596: E/AndroidRuntime(2464): at com.crumbin.tabs.HomeActivity$AsyncLoader.onPostExecute(HomeActivity.java:1) 01-22 13:11:34.596: E/AndroidRuntime(2464): at android.os.AsyncTask.finish(AsyncTask.java:602) 01-22 13:11:34.596: E/AndroidRuntime(2464): at android.os.AsyncTask.access$600(AsyncTask.java:156) 01-22 13:11:34.596: E/AndroidRuntime(2464): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615) 01-22 13:11:34.596: E/AndroidRuntime(2464): at android.os.Handler.dispatchMessage(Handler.java:99) 01-22 13:11:34.596: E/AndroidRuntime(2464): at android.os.Looper.loop(Looper.java:137) 01-22 13:11:34.596: E/AndroidRuntime(2464): at android.app.ActivityThread.main(ActivityThread.java:4424) 01-22 13:11:34.596: E/AndroidRuntime(2464): at java.lang.reflect.Method.invokeNative(Native Method) 01-22 13:11:34.596: E/AndroidRuntime(2464): at java.lang.reflect.Method.invoke(Method.java:511) 01-22 13:11:34.596: E/AndroidRuntime(2464): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 01-22 13:11:34.596: E/AndroidRuntime(2464): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 01-22 13:11:34.596: E/AndroidRuntime(2464): at dalvik.system.NativeStart.main(Native Method) 没有数据加载,循环甚至没有执行到 OnpostExecute()。错误可能是什么呢?我没获得错误信息,因为程序没执行到那一块。 我把数据加载到list 中,还是不能正常运行。如果不使用 AsyncTask,可以正常运行。 这是什么问题呢?
程序运行时强制关闭,可能为空指针
日志:java.lang.RuntimeException: Unable to start activity ComponentInfo{pcAlarm.pack/pcAlarm.pack.PCAlarmActivity}: java.lang.NumberFormatException: 空指针错误,可能在 private void readSaveAlarm(){ SharedPreferences sp =getContext().getSharedPreferences(PCAlarmActivity.class.getName(), Context.MODE_PRIVATE); String content=sp.getString(KEY_ALARM_LIST, null); if (content!=null) { String[] timeString=content.split(","); for (String string : timeString) { adapter.add(new AlarmData(Long.parseLong(string))); } } }方法里 package pcAlarm.pack; import java.util.ArrayList; import java.util.Calendar; import java.util.Currency; import java.util.List; import pcAlarm.pack.PCAlarmActivity; import android.app.Activity; import android.app.AlertDialog; import android.app.PendingIntent.OnFinished; import android.app.TimePickerDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.provider.Contacts; import android.view.View; import android.widget.ArrayAdapter; import pcAlarm.pack.AlarmView; import pcAlarm.pack.AlarmView.AlarmData; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TabHost; import android.widget.TimePicker; public class PCAlarmActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tabHost = (TabHost)findViewById(android.R.id.tabhost); tabHost.setup(); tabHost.addTab(tabHost.newTabSpec("tabAlarm").setIndicator("闹钟").setContent(R.id.tabAlarm)); btnAddAlarm=(Button)findViewById(R.id.btnAddAlarm); lvListView=(ListView)findViewById(R.id.lvListView); adapter=new ArrayAdapter<PCAlarmActivity.AlarmData>(getContext(), android.R.layout.simple_list_item_1); lvListView.setAdapter(adapter); adapter.add(new AlarmData(System.currentTimeMillis())); readSaveAlarm(); btnAddAlarm.setOnClickListener(new OnClickListener() { private Calendar mcalender; @Override public void onClick(View v) { Calendar.getInstance().setTimeInMillis(System.currentTimeMillis()); mcalender = Calendar.getInstance(); int mHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); int mMinute = Calendar.getInstance().get(Calendar.MINUTE); new TimePickerDialog(PCAlarmActivity.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { // TODO Auto-generated method stub Calendar.getInstance().setTimeInMillis(System.currentTimeMillis()); Calendar.getInstance().set(Calendar.HOUR_OF_DAY, hourOfDay); Calendar.getInstance().set(Calendar.MINUTE, minute); Calendar.getInstance().set(Calendar.SECOND, 0); Calendar.getInstance().set(Calendar.MILLISECOND, 0); AlarmData add = new AlarmData(Calendar.getInstance().getTimeInMillis()); saveAlarmList(); } }, mHour, mMinute, true).show(); } }); lvListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View arg1, final int position, long id) { new AlertDialog.Builder(getContext()).setTitle("操作选项").setItems(new CharSequence[]{"删除"}, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: deleteAlarm(position); break; default: break; } } }).setNegativeButton("取消", null).show(); return true; } }); } private void deleteAlarm(int position){ adapter.remove(adapter.getItem(position)); } private void saveAlarmList(){ Editor editor=getContext().getSharedPreferences(PCAlarmActivity.class.getCanonicalName(), Context.MODE_PRIVATE).edit(); StringBuffer sb=new StringBuffer(); for (int i = 0; i < adapter.getCount(); i ) { sb.append(adapter.getItem(i).getTime()).append(","); } String content = sb.toString().substring(0, sb.length()-1); editor.putString(KEY_ALARM_LIST, sb.toString().substring(0, sb.length())); System.out.println(); editor.commit(); }
老是获取到position的最后一个值
不管按哪个按钮,上一次老是获取到position的第一个值,显示"苹果",然后按照网上的解决办法改了之后,老是获取到position的最后一个值,显示"运行" ![图片说明](https://img-ask.csdn.net/upload/201705/11/1494472503_511184.png) ``` package com.example.exer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.AlertDialog; import android.app.ListActivity; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends ListActivity { private static final String TAG = "MainActivity"; private List<Map<String, Object>> mdata; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); ListView mListView=getListView(); mdata = data(); mListView.setAdapter(new MyAdapter(this,mdata)); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> l, View v, int position, long id) { Log.i(TAG, (String)mdata.get(position).get("title")); Toast.makeText(MainActivity.this, (String)mdata.get(position).get("title"), 1000).show(); } }); } class MyAdapter extends BaseAdapter{ private Context context; Hodler hodler =null; private LayoutInflater minflater; private ArrayList<Map<String,Object>> datalist; public MyAdapter(Context context,List<Map<String,Object>> datalist) { this.context=context; this.minflater = LayoutInflater.from(context); this.datalist=(ArrayList<Map<String,Object>>)datalist; } @Override public int getCount() { // TODO Auto-generated method stub return datalist.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return datalist.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null){ hodler = new Hodler(); convertView= minflater.inflate(R.layout.mylist, null); hodler.img = (ImageView) convertView.findViewById(R.id.img); hodler.title = (TextView) convertView.findViewById(R.id.title); hodler.info = (TextView) convertView.findViewById(R.id.info); hodler.button = (Button) convertView.findViewById(R.id.button); convertView.setTag(hodler); }else{ hodler = (Hodler)convertView.getTag(); } hodler.img.setBackgroundResource((Integer) mdata.get(position).get("img")); hodler.title.setText((CharSequence) mdata.get(position).get("title")); hodler.info.setText((CharSequence) mdata.get(position).get("info")); //hodler.button.setTag(position); hodler.positio=position; hodler.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //showdialog((int)hodler.button.getTag()); showdialog(hodler.positio); } }); return convertView; } class Hodler { public ImageView img; public TextView title; public TextView info; public Button button; int positio;//增加一个变量记录每个item的值 } } public void showdialog(int position) { new AlertDialog.Builder(this).setTitle("提示信息").setMessage("你点击的标题是: " +(String)mdata.get(position).get("title")) .setPositiveButton("确定", new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this, "确定", Toast.LENGTH_SHORT).show(); setResult(RESULT_OK); finish(); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); } public List<Map<String, Object>> data() { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> map = new HashMap<String, Object>(); map.put("title", "苹果"); map.put("info", "apple"); map.put("img", R.drawable.ic_launcher); list.add(map); map = new HashMap<String, Object>(); map.put("title", "书"); map.put("info", "book"); map.put("img", R.drawable.ic_launcher); list.add(map); map = new HashMap<String, Object>(); map.put("title", "电脑"); map.put("info", "computer"); map.put("img", R.drawable.ic_launcher); list.add(map); map = new HashMap<String, Object>(); map.put("title", "对话"); map.put("info", "dialog"); map.put("img", R.drawable.ic_launcher); list.add(map); map = new HashMap<String, Object>(); map.put("title", "运行"); map.put("info", "run"); map.put("img", R.drawable.ic_launcher); list.add(map); return list; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } ```
按钮按了有反应,可onItemClick却没执行到
![图片说明](https://img-ask.csdn.net/upload/201705/10/1494389301_214240.png) ![图片说明](https://img-ask.csdn.net/upload/201705/10/1494389320_136211.jpg) 1.按钮按了有反应,可onItemClick却没执行到 2.无论按哪个按钮,都显示"你点击的标题是:苹果" ``` package com.example.exer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.AlertDialog; import android.app.ListActivity; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends ListActivity { private static final String TAG = "MainActivity"; private List<Map<String, Object>> mdata; private int positio; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); ListView mListView=getListView(); mdata = data(); mListView.setAdapter(new MyAdapter(this,mdata)); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> l, View v, int position, long id) { Log.i(TAG, (String)mdata.get(position).get("title")); Toast.makeText(MainActivity.this, (String)mdata.get(position).get("title"), 1000).show(); } }); } class MyAdapter extends BaseAdapter{ private Context context; private LayoutInflater minflater; private ArrayList<Map<String,Object>> datalist; public MyAdapter(Context context,List<Map<String,Object>> datalist) { this.context=context; this.minflater = LayoutInflater.from(context); this.datalist=(ArrayList<Map<String,Object>>)datalist; } @Override public int getCount() { // TODO Auto-generated method stub return datalist.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return datalist.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub positio=position; return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { Hodler hodler =null; if(convertView == null){ hodler = new Hodler(); convertView = minflater.inflate(R.layout.mylist, null); hodler.img = (ImageView) convertView.findViewById(R.id.img); hodler.title = (TextView) convertView.findViewById(R.id.title); hodler.info = (TextView) convertView.findViewById(R.id.info); hodler.button = (Button) convertView.findViewById(R.id.button); convertView.setTag(hodler); }else{ hodler = (Hodler) convertView.getTag(); } hodler.img.setBackgroundResource((Integer) mdata.get(position).get("img")); hodler.title.setText((CharSequence) mdata.get(position).get("title")); hodler.info.setText((CharSequence) mdata.get(position).get("info")); hodler.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showdialog(); } }); return convertView; } class Hodler { public ImageView img; public TextView title; public TextView info; public Button button; } } public void showdialog() { new AlertDialog.Builder(this).setTitle("提示信息").setMessage("你点击的标题是: " +(String)mdata.get(positio).get("title")) .setPositiveButton("确定", new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this, "确定", 1000).show(); setResult(RESULT_OK); finish(); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); } public List<Map<String, Object>> data() { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> map = new HashMap<String, Object>(); map.put("title", "苹果"); map.put("info", "apple"); map.put("img", R.drawable.ic_launcher); list.add(map); map = new HashMap<String, Object>(); map.put("title", "书"); map.put("info", "book"); map.put("img", R.drawable.ic_launcher); list.add(map); map = new HashMap<String, Object>(); map.put("title", "电脑"); map.put("info", "computer"); map.put("img", R.drawable.ic_launcher); list.add(map); map = new HashMap<String, Object>(); map.put("title", "对话"); map.put("info", "dialog"); map.put("img", R.drawable.ic_launcher); list.add(map); map = new HashMap<String, Object>(); map.put("title", "运行"); map.put("info", "run"); map.put("img", R.drawable.ic_launcher); list.add(map); return list; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } ```
两个Activity之间Intent跳转问题
public class Sports extends TabActivity implements OnTabChangeListener{ private TabHost myTabhost; protected int myMenuSettingTag=0; private ListView listView,listView2; private String strArr[] = {"野外登山","高山蹦极","徒步远足","海滩沐浴"}; private Button button1 = null; private CheckBox checkBox1,checkBox2,checkBox3,checkBox4,checkBox5,checkBox6; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); checkBox1=(CheckBox)findViewById(R.id.checkBox1); checkBox2=(CheckBox)findViewById(R.id.checkBox2); checkBox3=(CheckBox)findViewById(R.id.checkBox3); checkBox4=(CheckBox)findViewById(R.id.checkBox4); checkBox5=(CheckBox)findViewById(R.id.checkBox5); checkBox6=(CheckBox)findViewById(R.id.checkBox6); myTabhost=this.getTabHost(); LayoutInflater.from(this).inflate(R.layout.sports, myTabhost.getTabContentView(), true); myTabhost.setBackgroundResource(R.drawable.backgroud3); myTabhost .addTab(myTabhost.newTabSpec("One") .setIndicator("球类运动", getResources().getDrawable(R.drawable.tab1)) .setContent(R.id.tab1)); myTabhost .addTab(myTabhost.newTabSpec("Two") .setIndicator("水上项目", getResources().getDrawable(R.drawable.tab2)) .setContent(R.id.tab2)); myTabhost .addTab(myTabhost.newTabSpec("Three") .setIndicator("野外项目", getResources().getDrawable(R.drawable.tab3)) .setContent(R.id.tab3)); listView=(ListView)findViewById(R.id.listView); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, strArr); listView.setAdapter(arrayAdapter); myTabhost .addTab(myTabhost.newTabSpec("Four") .setIndicator("专业健身", getResources().getDrawable(R.drawable.tab4)) .setContent(R.id.tab4)); listView2=(ListView)findViewById(R.id.listView2); SimpleAdapter adapter = new SimpleAdapter(this,getList(), R.layout.vlist, new String[]{"title","img"}, new int[]{R.id.title,R.id.img}); listView2.setAdapter(adapter); myTabhost.setOnTabChangedListener(this); myTabhost.setOnTabChangedListener(new OnTabChangeListener() { @Override public void onTabChanged(String tabId) { // TODO Auto-generated method stub } }); } private ArrayList<HashMap<String, Object>> getList() { ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>(); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("title", "器械运动(拉力器、俯卧撑等)"); map.put("img", R.drawable.sports1); list.add(map); map = new HashMap<String, Object>(); map.put("title", "有氧运动(跑步、健美操等)"); map.put("img", R.drawable.sports2); list.add(map); map = new HashMap<String, Object>(); map.put("title", "拉伸运动(瑜伽、普拉提等)"); map.put("img", R.drawable.sports3); list.add(map); return list; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if(keyCode==KeyEvent.KEYCODE_BACK){ Intent intent=new Intent(); intent.setClass(Sports.this,MainActivity.class); startActivity(intent); Sports.this.finish(); } return super.onKeyDown(keyCode, event); } @Override public void onTabChanged(String arg0) { // TODO Auto-generated method stub if (arg0.equals("One")) { button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Dialog dialog=new AlertDialog.Builder(Sports.this) .setTitle("状态") .setMessage("本程序由Easy制作\nVersion 0.01") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }).create(); dialog.show(); } }); } if (arg0.equals("Two")) { myMenuSettingTag = 2; } if (arg0.equals("Three")) { myMenuSettingTag = 3; } if (arg0.equals("Four")) { myMenuSettingTag = 4; } } } 这是sports.java public class SportsCheck extends Activity { private Button button01 = null; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sports); button01=(Button)findViewById(R.id.button1); button01.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent=new Intent(); intent.setClass(SportsCheck.this,SportsCheck1.class); startActivity(intent); SportsCheck.this.finish(); } }); } public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if(keyCode==KeyEvent.KEYCODE_BACK){ Intent intent=new Intent(); intent.setClass(SportsCheck.this,SportsCheck1.class); startActivity(intent); SportsCheck.this.finish(); } return super.onKeyDown(keyCode, event); } } 这是Sportscheck.Java public class SportsCheck1 extends Activity { private Button button1=null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sportscheck1); button1=(Button)findViewById(R.id.back); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent=new Intent(); intent.setClass(SportsCheck1.this,SportsCheck.class); startActivity(intent); SportsCheck1.this.finish(); } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if(keyCode==KeyEvent.KEYCODE_BACK){ Intent intent=new Intent(); intent.setClass(SportsCheck1.this,SportsCheck.class); startActivity(intent); SportsCheck1.this.finish(); } return super.onKeyDown(keyCode, event); } } 这是sportscheck1.java ``` ```
android adapter空指针异常
``` public class MainActivity extends AppCompatActivity { DatabaseHelper databaseHelper; private static Toolbar mToolbar; private static TextView mMaintitle,mMaincontent,mMaintime; public static EditText dlx_Input1,dlx_Input2; public static String datetime; public static View mLine; MyAdapter myAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findName(); setSupportActionBar(mToolbar); databaseHelper = new DatabaseHelper(this, databaseHelper.DATABASE_NAME, null, databaseHelper.DATABASE_VERSION); //myAdapter.getData2(); myAdapter = new MyAdapter(this); myAdapter.lv = (ListView)findViewById(R.id.lv); myAdapter.data = myAdapter.getData(); MyAdapter adapter = new MyAdapter(this); myAdapter.lv.setAdapter(adapter); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_add: showDialog_Layout(MainActivity.this); } return super.onOptionsItemSelected(item); } public void findName() { mToolbar = (Toolbar) findViewById(R.id.toolbar); mMaintitle = (TextView)findViewById(R.id.dlx_maintitle); mMaincontent = (TextView)findViewById(R.id.dlx_maincontent); mMaintime = (TextView)findViewById(R.id.dlx_maintime); mLine = (View)findViewById(R.id.dlx_line); } private void showDialog_Layout(Context context) { dlx_Input1 = (EditText)findViewById(R.id.dlx_Input1); dlx_Input2 = (EditText)findViewById(R.id.dlx_Input2); final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setCancelable(false); builder.setTitle(R.string.dlx_add); builder.setPositiveButton("CANCEL", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { setTitle(""); } }); builder.setNegativeButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { SQLiteDatabase db = databaseHelper.getWritableDatabase(); ContentValues values = new ContentValues(); SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); datetime = s.format(new java.util.Date()); values.put("title", String.valueOf(dlx_Input1.getText())); values.put("content", String.valueOf(dlx_Input2.getText())); values.put("time", datetime); db.insert(databaseHelper.TABLE_NAME, null, values); myAdapter.getData(); } }); builder.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); menu.findItem(R.id.action_add).setChecked(true); return super.onCreateOptionsMenu(menu); } } public class MyAdapter extends BaseAdapter { public static ListView lv; public static List<Map<String, Object>> data; public LayoutInflater mInflater = null; MainActivity mainActivity; DatabaseHelper databaseHelper; public MyAdapter(Context context) { this.mInflater = LayoutInflater.from(context); } public List<Map<String, Object>> getData() { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> map; for(int i=0;i<10;i++) { map = new HashMap<String, Object>(); map.put("title",String.valueOf(mainActivity.dlx_Input1.getText())); map.put("content", String.valueOf(mainActivity.dlx_Input2.getText())); map.put("time",mainActivity.datetime); list.add(map); } return list; } static class ViewHolder { public TextView title; public TextView content; public TextView time; public View line; } public int getCount() { //How many items are in the data set represented by this Adapter. //在此适配器中所代表的数据集中的条目数 return data.size(); } public Object getItem(int position) { // Get the data item associated with the specified position in the data set. //获取数据集中与指定索引对应的数据项 return position; } public long getItemId(int position) { //Get the row id associated with the specified position in the list. //获取在列表中与指定索引对应的行id return position; } //Get a View that displays the data at the specified position in the data set. //获取一个在数据集中指定索引的视图来显示数据 public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; //如果缓存convertView为空,则需要创建View if(convertView == null) { holder = new ViewHolder(); //根据自定义的Item布局加载布局 convertView = mInflater.inflate(R.layout.commentlayout, null); holder.title = (TextView)convertView.findViewById(R.id.dlx_maintitle); holder.content = (TextView)convertView.findViewById(R.id.dlx_maincontent); holder.time = (TextView)convertView.findViewById(R.id.dlx_maintime); holder.line = (View)convertView.findViewById(R.id.dlx_line); //将设置好的布局保存到缓存中,并将其设置在Tag里,以便后面方便取出Tag convertView.setTag(holder); }else { holder = (ViewHolder)convertView.getTag(); } holder.title.setText((String)data.get(position).get("title")); holder.content.setText((String)data.get(position).get("content")); holder.time.setText((String)data.get(position).get("time")); holder.line.setBackgroundColor(mainActivity.getResources().getColor(R.color.colorPrimaryDark)); return convertView; } ``` 在map.put("title",String.valueOf(mainActivity.dlx_Input1.getText()));和myAdapter.data = myAdapter.getData();报空指针异常 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference,求大神指点!!!
利用线程获取json数据,肯定能获取到,可是为空
利用线程获取json数据,肯定能获取到,获取到的json传给公有的json,可是每次公有的json里面都是空值,求大神给解决方案。 我的代码 package textview.exam; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import com.baidu.apistore.sdk.ApiCallBack; import com.baidu.apistore.sdk.ApiStoreSDK; import com.baidu.apistore.sdk.network.Parameters; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class FragmentMainchatweather extends Fragment { TextView mTextView; Button test; String city; WeatherPopup weatherPopup; JSONArray forecast; ListView list; JSONObject retData=null; private int[] weatherzt = new int[] { R.drawable.sun , R.drawable.cloudy , R.drawable.baoyu , R.drawable.thouder,R.drawable.snow,R.drawable.zhongyu, R.drawable.zhenyu,R.drawable.dayu}; @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // TODO Auto-generated method stub View view=inflater.inflate(R.layout.main_chat_weather, null); Button weatheradd=(Button)view.findViewById(R.id.weatheradd); list = (ListView) view.findViewById(R.id.chat_weathers); list.setOnItemClickListener(weatherforListener); weatheradd.setOnClickListener(weatheraddListener); return view; } //点击添加按钮弹出输入城市对话框,然后根据城市名字进行查询并且显示 View.OnClickListener weatheraddListener=new View.OnClickListener() { @Override public void onClick(View v) { //加载文本框布局 final View weatheradd=getActivity().getLayoutInflater().inflate(R.layout.weatheradd, null); new AlertDialog.Builder(getActivity()) .setView(weatheradd) .setPositiveButton("确定",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { TextView city1=(TextView)weatheradd.findViewById(R.id.citytext); city=city1.getText().toString(); Log.i("我靠"+retData,"1"); SyncThread st1 = new SyncThread(); st1.start(); Log.i("我靠"+retData,"2"); //view更新 weatherselect(); } }) .setNegativeButton("取消",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .create() .show(); } }; AdapterView.OnItemClickListener weatherforListener=new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //为未来天气设置SimpleAdapter //final SimpleAdapter simpleAdapter1 = new SimpleAdapter(getActivity(), listItemx, R.layout.weather_popup_item, // new String[]{"forecastweek", "forecasttype", "forecastlowtemp", "forecasthightemp"}, // new int[]{R.id.forecastweek, R.id.forecasttype, R.id.forecastlowtemp, R.id.forecasthightemp}); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //实例化SelectPicPopupWindow weatherPopup = new WeatherPopup(getActivity()); //weatherPopup.setAdapter(simpleAdapter1); //显示窗口 weatherPopup.showAtLocation(getActivity().findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); } }); } }; public void weatherselect(){ List<Map<String, Object>> listItemx = new ArrayList<Map<String, Object>>(); try { Map<String, Object> listItem = new HashMap<String, Object>(); JSONObject today = retData.getJSONObject("today"); listItem.put("city", retData.getString("city")); listItem.put("lowtemp", today.getString("lowtemp")); listItem.put("hightemp", today.getString("hightemp")); listItem.put("week", today.getString("week")); listItem.put("curTemp", today.getString("curTemp")); listItem.put("type", today.getString("type")); listItem.put("fengli", today.getString("fengli")); listItem.put("aqi", today.getString("aqi")); listItemx.add(listItem); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getActivity(),"数据加载错误", Toast.LENGTH_LONG).show(); } final SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(), listItemx, R.layout.weather_simple_item, new String[]{"city", "lowtemp", "hightemp", "week", "curTemp", "type", "fengli", "aqi"}, new int[]{R.id.city, R.id.lowtemp, R.id.hightemp, R.id.week, R.id.curTemp, R.id.type, R.id.fengli, R.id.aqi}) { @Override public View getView(int position, View convertView,ViewGroup parent){ final View view=super.getView(position, convertView, parent); TextView text=(TextView)view.findViewById(R.id.type); switch (text.getText().toString()){ case "多云": view.setBackgroundResource(weatherzt[1]); break; case "雷阵雨": view.setBackgroundResource(weatherzt[3]); break; case "阵雨": view.setBackgroundResource(weatherzt[6]); break; case "大雨": view.setBackgroundResource(weatherzt[7]); break; case "暴雨": view.setBackgroundResource(weatherzt[2]); break; case "晴": view.setBackgroundResource(weatherzt[0]); break; case "雪": view.setBackgroundResource(weatherzt[4]); break; case "中雨": view.setBackgroundResource(weatherzt[5]); break; default: view.setBackgroundResource(weatherzt[0]); break; } return view; } }; simpleAdapter.notifyDataSetChanged(); list.setAdapter(simpleAdapter); } //开启子线程得到数据 public class SyncThread extends Thread { @Override public void run() { Parameters para = new Parameters(); para.put("cityname", city); ApiStoreSDK.execute("http://apis.baidu.com/apistore/weatherservice/recentweathers", ApiStoreSDK.GET, para, new ApiCallBack() { @Override public void onSuccess(int status, String responseString) { Log.i("连接状态(天气)", "成功"); try { JSONObject dataJson = new JSONObject(responseString); retData = dataJson.getJSONObject("retData"); Log.i("我靠" + retData, "3"); } catch (JSONException e) { Toast toast = Toast.makeText(getActivity(), "没有这个城市请重新输入", Toast.LENGTH_SHORT); //屏幕下方显示,X轴和Y轴偏移量都是0 toast.setGravity(Gravity.BOTTOM, 0, 0); toast.show(); Log.i("获取到数据:", responseString); } } @Override public void onComplete() { Log.i("sdkdemo", "onComplete"); } @Override public void onError(int status, String responseString, Exception e) { Log.i("sdkdemo", "onError, status: " + status); Log.i("sdkdemo", "errMsg: " + (e == null ? "" : e.getMessage())); } }); } } }
关于安卓页面跳转的问题
做了两个页面与页面跳转按钮,二页面想使用ListActivity,但是继承了ListActivity类后闪退 继承Activity时运行正常,但不能看到List效果,请大神帮忙看下代码,感谢 DEBUG 线程 [main](已暂挂(异常 RuntimeException)) ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) 行: 3254 ActivityThread.handleLaunchActivity(ActivityThread$ActivityClientRecord, Intent) 行: 3350 ActivityThread.access$1100(ActivityThread, ActivityThread$ActivityClientRecord, Intent) 行: 223 ActivityThread$H.handleMessage(Message) 行: 1794 ActivityThread$H(Handler).dispatchMessage(Message) 行: 102 Looper.loop() 行: 148 ActivityThread.main(String[]) 行: 7224 Method.invoke(Object, Object...) 行: 不可用 [本机方法] ZygoteInit$MethodAndArgsCaller.run() 行: 1230 ZygoteInit.main(String[]) 行: 1120 报错日志 04-11 10:03:01.957: E/MotionRecognitionManager(30956): mSContextService = android.hardware.scontext.ISContextService$Stub$Proxy@b530bca 04-11 10:03:01.967: E/MotionRecognitionManager(30956): motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy@82fc13b 04-11 10:03:01.967: E/MotionRecognitionManager(30956): motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy@82fc13b 04-11 10:03:01.967: D/AndroidRuntime(30956): Shutting down VM 04-11 10:03:01.967: E/AndroidRuntime(30956): FATAL EXCEPTION: main 04-11 10:03:01.967: E/AndroidRuntime(30956): Process: com.example.audiorecord, PID: 30956 04-11 10:03:01.967: E/AndroidRuntime(30956): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.audiorecord/com.example.audiorecord.Activity02}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list' 04-11 10:03:01.967: E/AndroidRuntime(30956): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3254) 04-11 10:03:01.967: E/AndroidRuntime(30956): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350) 04-11 10:03:01.967: E/AndroidRuntime(30956): at android.app.ActivityThread.access$1100(ActivityThread.java:223) 04-11 10:03:01.967: E/AndroidRuntime(30956): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794) 04-11 10:03:01.967: E/AndroidRuntime(30956): at android.os.Handler.dispatchMessage(Handler.java:102) 04-11 10:03:01.967: E/AndroidRuntime(30956): at android.os.Looper.loop(Looper.java:148) 04-11 10:03:01.967: E/AndroidRuntime(30956): at android.app.ActivityThread.main(ActivityThread.java:7224) 04-11 10:03:01.967: E/AndroidRuntime(30956): at java.lang.reflect.Method.invoke(Native Method) 04-11 10:03:01.967: E/AndroidRuntime(30956): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 04-11 10:03:01.967: E/AndroidRuntime(30956): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 04-11 10:03:01.967: E/AndroidRuntime(30956): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list' 04-11 10:03:01.967: E/AndroidRuntime(30956): at android.app.ListActivity.onContentChanged(ListActivity.java:243) 04-11 10:03:01.967: E/AndroidRuntime(30956): at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:479) 04-11 10:03:01.967: E/AndroidRuntime(30956): at android.app.Activity.setContentView(Activity.java:2388) 04-11 10:03:01.967: E/AndroidRuntime(30956): at com.example.audiorecord.Activity02.onCreate(Activity02.java:38) 04-11 10:03:01.967: E/AndroidRuntime(30956): at android.app.Activity.performCreate(Activity.java:6877) 04-11 10:03:01.967: E/AndroidRuntime(30956): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136) 04-11 10:03:01.967: E/AndroidRuntime(30956): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3207) 04-11 10:03:01.967: E/AndroidRuntime(30956): ... 9 more Activity1: package com.example.audiorecord; import java.io.File; import java.io.IOException; import android.app.Activity; import android.media.MediaPlayer; import android.media.MediaRecorder; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.content.Intent; public class RecordActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); super.onCreate(savedInstanceState); /* 设置显示main.xml布局*/ setContentView(R.layout.main); /* findViewById(R.id.button1)取得布局main.xml中的button1 */ Button button = (Button) findViewById(R.id.button1); /* 监听button的事件信息*/ button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { /* 新建一个Intent对象*/ Intent intent = new Intent(); /* 指定intent要启动的类*/ intent.setClass(RecordActivity.this, Activity02.class); /* 启动一个新的Activity */ startActivity(intent); /* 关闭当前的Activity */ RecordActivity.this.finish(); } }); } } Activity2 package com.example.audiorecord; import java.io.File; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; public class Activity02 extends ListActivity{ //声明 private List<String> items = null;//存放名称 private List<String> paths = null;//存放路径 private String rootPath = "/"; private TextView tv; private Button Back; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* 设置显示main2布局*/ setContentView(R.layout.main2); /* findViewById(R.id.button2)取得布局main.xml中的button2 */ /* 监听button的事件信息*/ tv = (TextView) this.findViewById(R.id.TextView); this.getFileDir(rootPath);//获取rootPath目录下的文件. Back = (Button) findViewById(R.id.back); Back.setOnClickListener(new BackListener()); } class BackListener implements OnClickListener { public void onClick(View v) { Intent intent = new Intent(); /* 指定intent要启动的类*/ intent.setClass(Activity02.this, RecordActivity.class); /* 启动一个新的Activity */ startActivity(intent); /* 关闭当前的Activity */ Activity02.this.finish(); } } public void getFileDir(String filePath) { try{ this.tv.setText("当前路径:"+filePath);// 设置当前所在路径 items = new ArrayList<String>(); paths = new ArrayList<String>(); File f = new File(filePath); File[] files = f.listFiles();// 列出所有文件 // 如果不是根目录,则列出返回根目录和上一目录选项 if (!filePath.equals(rootPath)) { items.add("返回根目录"); paths.add(rootPath); items.add("返回上一层目录"); paths.add(f.getParent()); } // 将所有文件存入list中 if(files != null){ int count = files.length;// 文件个数 for (int i = 0; i < count; i++) { File file = files[i]; items.add(file.getName()); paths.add(file.getPath()); } } ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items); this.setListAdapter(adapter); }catch(Exception ex){ ex.printStackTrace(); } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); String path = paths.get(position); File file = new File(path); //如果是文件夹就继续分解 if(file.isDirectory()){ this.getFileDir(path); }else{ new AlertDialog.Builder(this).setTitle("提示").setMessage(file.getName()+" 是一个文件!").setPositiveButton("OK", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { } }).show(); } }} MANIFEST <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.audiorecord" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="4" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".RecordActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".Activity02"></activity> </application> </manifest>
Android中重写SimpleAdapter类引用后报空指针异常
直接粘代码吧 - - 重写的SimpleAdapter类: ``` public class MySimpleAdapter extends BaseAdapter { private LayoutInflater mInflater; private ArrayList<HashMap<String, Object>> list; private int layoutID; private String flag[]; private int ItemIDs[]; public MySimpleAdapter(Context context, ArrayList<HashMap<String, Object>> list, int layoutID, String flag[], int ItemIDs[]) { this.mInflater = LayoutInflater.from(context); this.list = list; this.layoutID = layoutID; this.flag = flag; this.ItemIDs = ItemIDs; } @Override public int getCount() { // TODO Auto-generated method stub return list.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return 0; } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = mInflater.inflate(layoutID, null); convertView = mInflater.inflate(layoutID, null); for (int i = 0; i < flag.length; i++) { if (convertView.findViewById(ItemIDs[i]) instanceof ImageView) { ImageView iv = (ImageView) convertView.findViewById(ItemIDs[i]); iv.setBackgroundResource((Integer) list.get(position).get( flag[i])); } else if (convertView.findViewById(ItemIDs[i]) instanceof TextView) { TextView tv = (TextView) convertView.findViewById(ItemIDs[i]); tv.setText((String) list.get(position).get(flag[i])); } } addListener(convertView); return convertView; } public void addListener(View convertView) { ((TextView)convertView.findViewById(R.id.order_mine_show_handle_confirm)).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { new AlertDialog.Builder(OrderMineNonPaymentActivity.onp) .setTitle("自定义通用SimpleAdapter") .setMessage("按钮成功触发监听事件!") .show(); } }); } } ``` 引用的地方 OrderMineNonPaymentActivity: ``` /** * 动态生成订单列表 lipeng */ private void addNonPaymentList() { order_mine_show_non_payment_list_ll = (LinearLayout) findViewById(R.id.order_mine_show_non_payment_list_ll); nonPaymentList = (ListView) findViewById(R.id.order_mine_show_non_payment_list); nonPaymentList.setDivider(null); nonPaymentSimpleAdapter = new SimpleAdapter( OrderMineNonPaymentActivity.this, goodsList, R.layout.activity_order_non_payment_item, new String[] { "shopname", "bigimage", "goodname" }, new int[] { R.id.order_mine_show_shopname, R.id.order_mine_show_goods_img, R.id.order_mine_show_goods_name }); MySimpleAdapter nonPaymentSimpleAdapter = new MySimpleAdapter(this, goodsList, R.layout.activity_order_mine_non_payment, new String[] { "shopname", "bigimage", "goodname" }, new int[] { R.id.order_mine_show_shopname, R.id.order_mine_show_goods_img, R.id.order_mine_show_goods_name }); nonPaymentList.setAdapter(nonPaymentSimpleAdapter); } private class MyOnItemClickListener implements OnItemClickListener { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub } } ``` 异常报的空指针,找了半天也没找到为啥空指针了 ``` 06-17 22:55:32.845: E/AndroidRuntime(1463): FATAL EXCEPTION: main 06-17 22:55:32.845: E/AndroidRuntime(1463): Process: com.zb.stlala, PID: 1463 06-17 22:55:32.845: E/AndroidRuntime(1463): java.lang.NullPointerException 06-17 22:55:32.845: E/AndroidRuntime(1463): at com.zb.stlala.adapter.MySimpleAdapter.addListener(MySimpleAdapter.java:83) 06-17 22:55:32.845: E/AndroidRuntime(1463): at com.zb.stlala.adapter.MySimpleAdapter.getView(MySimpleAdapter.java:75) ```
爬虫福利二 之 妹子图网MM批量下载
爬虫福利一:27报网MM批量下载    点击 看了本文,相信大家对爬虫一定会产生强烈的兴趣,激励自己去学习爬虫,在这里提前祝:大家学有所成! 目标网站:妹子图网 环境:Python3.x 相关第三方模块:requests、beautifulsoup4 Re:各位在测试时只需要将代码里的变量 path 指定为你当前系统要保存的路径,使用 python xxx.py 或IDE运行即可。
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 顺便拉下票,我在参加csdn博客之星竞选,欢迎投票支持,每个QQ或者微信每天都可以投5票,扫二维码即可,http://m234140.nofollow.ax.
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入 假设现有4个人...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 欢迎 改进 留言。 演示地点跳到演示地点 html代码如下`&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;music&lt;/title&gt; &lt;meta charset="utf-8"&gt
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。 1. for - else 什么?不是 if 和 else 才
数据库优化 - SQL优化
前面一篇文章从实例的角度进行数据库优化,通过配置一些参数让数据库性能达到最优。但是一些“不好”的SQL也会导致数据库查询变慢,影响业务流程。本文从SQL角度进行数据库优化,提升SQL运行效率。 判断问题SQL 判断SQL是否有问题时可以通过两个表象进行判断: 系统级别表象 CPU消耗严重 IO等待严重 页面响应时间过长
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 c/c++ 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7
通俗易懂地给女朋友讲:线程池的内部原理
餐厅的约会 餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”我楞了一下,心里想女朋友今天是怎么了,怎么突然问出这么专业的问题,但做为一个专业人士在女朋友面前也不能露怯啊,想了一下便说:“我先给你讲讲我前同事老王的故事吧!” 大龄程序员老王 老王是一个已经北漂十多年的程序员,岁数大了,加班加不动了,升迁也无望,于是拿着手里
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹
面试官:你连RESTful都不知道我怎么敢要你?
面试官:了解RESTful吗? 我:听说过。 面试官:那什么是RESTful? 我:就是用起来很规范,挺好的 面试官:是RESTful挺好的,还是自我感觉挺好的 我:都挺好的。 面试官:… 把门关上。 我:… 要干嘛?先关上再说。 面试官:我说出去把门关上。 我:what ?,夺门而去 文章目录01 前言02 RESTful的来源03 RESTful6大原则1. C-S架构2. 无状态3.统一的接
JDK12 Collectors.teeing 你真的需要了解一下
前言 在 Java 12 里面有个非常好用但在官方 JEP 没有公布的功能,因为它只是 Collector 中的一个小改动,它的作用是 merge 两个 collector 的结果,这句话显得很抽象,老规矩,我们先来看个图(这真是一个不和谐的图????): 管道改造经常会用这个小东西,通常我们叫它「三通」,它的主要作用就是将 downstream1 和 downstre...
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看
SQL-小白最佳入门sql查询一
不要偷偷的查询我的个人资料,即使你再喜欢我,也不要这样,真的不好;
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
【图解经典算法题】如何用一行代码解决约瑟夫环问题
约瑟夫环问题算是很经典的题了,估计大家都听说过,然后我就在一次笔试中遇到了,下面我就用 3 种方法来详细讲解一下这道题,最后一种方法学了之后保证让你可以让你装逼。 问题描述:编号为 1-N 的 N 个士兵围坐在一起形成一个圆圈,从编号为 1 的士兵开始依次报数(1,2,3…这样依次报),数到 m 的 士兵会被杀死出列,之后的士兵再从 1 开始报数。直到最后剩下一士兵,求这个士兵的编号。 1、方...
致 Python 初学者
欢迎来到“Python进阶”专栏!来到这里的每一位同学,应该大致上学习了很多 Python 的基础知识,正在努力成长的过程中。在此期间,一定遇到了很多的困惑,对未来的学习方向感到迷茫。我非常理解你们所面临的处境。我从2007年开始接触 python 这门编程语言,从2009年开始单一使用 python 应对所有的开发工作,直至今天。回顾自己的学习过程,也曾经遇到过无数的困难,也曾经迷茫过、困惑过。开办这个专栏,正是为了帮助像我当年一样困惑的 Python 初学者走出困境、快速成长。希望我的经验能真正帮到你
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
GitHub标星近1万:只需5秒音源,这个网络就能实时“克隆”你的声音
作者 | Google团队 译者 | 凯隐 编辑 | Jane 出品 | AI科技大本营(ID:rgznai100) 本文中,Google 团队提出了一种文本语音合成(text to speech)神经系统,能通过少量样本学习到多个不同说话者(speaker)的语音特征,并合成他们的讲话音频。此外,对于训练时网络没有接触过的说话者,也能在不重新训练的情况下,仅通过未知...
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1...
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员...
网易云6亿用户音乐推荐算法
网易云音乐是音乐爱好者的集聚地,云音乐推荐系统致力于通过 AI 算法的落地,实现用户千人千面的个性化推荐,为用户带来不一样的听歌体验。 本次分享重点介绍 AI 算法在音乐推荐中的应用实践,以及在算法落地过程中遇到的挑战和解决方案。 将从如下两个部分展开: AI算法在音乐推荐中的应用 音乐场景下的 AI 思考 从 2013 年 4 月正式上线至今,网易云音乐平台持续提供着:乐屏社区、UGC...
【技巧总结】位运算装逼指南
位算法的效率有多快我就不说,不信你可以去用 10 亿个数据模拟一下,今天给大家讲一讲位运算的一些经典例子。不过,最重要的不是看懂了这些例子就好,而是要在以后多去运用位运算这些技巧,当然,采用位运算,也是可以装逼的,不信,你往下看。我会从最简单的讲起,一道比一道难度递增,不过居然是讲技巧,那么也不会太难,相信你分分钟看懂。 判断奇偶数 判断一个数是基于还是偶数,相信很多人都做过,一般的做法的代码如下...
【管理系统课程设计】美少女手把手教你后台管理
【文章后台管理系统】URL设计与建模分析+项目源码+运行界面 栏目管理、文章列表、用户管理、角色管理、权限管理模块(文章最后附有源码) 1. 这是一个什么系统? 1.1 学习后台管理系统的原因 随着时代的变迁,现如今各大云服务平台横空出世,市面上有许多如学生信息系统、图书阅读系统、停车场管理系统等的管理系统,而本人家里就有人在用烟草销售系统,直接在网上完成挑选、购买与提交收货点,方便又快捷。 试想,若没有烟草销售系统,本人家人想要购买烟草,还要独自前往药...
4G EPS 第四代移动通信系统
目录 文章目录目录4G 与 LTE/EPCLTE/EPC 的架构E-UTRANE-UTRAN 协议栈eNodeBEPCMMES-GWP-GWHSSLTE/EPC 协议栈概览 4G 与 LTE/EPC 4G,即第四代移动通信系统,提供了 3G 不能满足的无线网络宽带化,主要提供数据(上网)业务。而 LTE(Long Term Evolution,长期演进技术)是电信领域用于手机及数据终端的高速无线通...
相关热词 c#选择结构应用基本算法 c# 收到udp包后回包 c#oracle 头文件 c# 序列化对象 自定义 c# tcp 心跳 c# ice连接服务端 c# md5 解密 c# 文字导航控件 c#注册dll文件 c#安装.net
立即提问