android listview setAdapter()方法导致闪退

代码如下,想要实现点击一个checkBox之后,弹出一个dialog,其中用listview来显示带有图标和应用信息的列表,但是运行之后会闪退,提示
listview.setAdapter(browseAppAdapter);
这行代码空指针错误,求解

            checkBox.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (checkBox.isChecked()) {
                    final Dialog dialog = new Dialog(getActivity());
                    dialog.setContentView(R.layout.browse_app_list);
                    dialog.setTitle("应用列表");

                    mlistAppInfo = new ArrayList<AppInfo>();
                    queryAppInfo(); // 查询所有应用程序信息
                    BrowseApplicationInfoAdapter browseAppAdapter = new BrowseApplicationInfoAdapter(
                            getActivity(), mlistAppInfo);   
                    listview.setAdapter(browseAppAdapter);
                    listview.setOnItemClickListener(new OnItemClickListener(){
                        @Override
                        public void onItemClick(AdapterView<?> arg0, View arg1,
                                int position, long arg3) {
                            // TODO Auto-generated method stub
                            intent = mlistAppInfo.get(position).getIntent();
                        }

                    });
                    dialog.show();
                }
            }
        });

5个回答

listview实例化了吗?

a774057695
leobert_lan 回复_Endless_: 实在抱歉啊,前一阵子一直没上网。。解决了就好啦
4 年多之前 回复
tuochichuang09
_Endless_ 你好,具体代码发在下面了,你可以看看,谢谢帮助!
4 年多之前 回复
tuochichuang09
_Endless_ listview = (ListView) view.findViewById(R.id.listviewApp);
4 年多之前 回复
tuochichuang09
_Endless_ 实例化了啊
4 年多之前 回复
tuochichuang09
_Endless_ 实例化了啊
4 年多之前 回复

listview之前的代码那?

tuochichuang09
_Endless_ 就是做了一个在viewpager中的fragment,里面有一个checkbox,在选择之后会弹出一个dialog,里面显示了所有的应用信息
4 年多之前 回复
tuochichuang09
_Endless_ 我发在下面你可以看看
4 年多之前 回复


 package com.example.gesture;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.example.gesture.R;
import com.example.gesture.ShakeDetector.OnShakeListener;

import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
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.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class MainTab01 extends Fragment {
    ShakeDetector mShakeDetector1;
    private CheckBox checkBox;
    private ListView listview = null;
    private List<AppInfo> mlistAppInfo = null;
    private Intent intent;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_tab_01, container, false);
        checkBox = (CheckBox) view.findViewById(R.id.checkBox1);
        listview = (ListView) view.findViewById(R.id.listviewApp);
        final ShakeDetector mShakeDetector = new ShakeDetector(
                this.getActivity());
        OnShakeListener shake = new OnShakeListener() {
            @Override
            public void onShake() {
                startActivity(intent);
            }

        };
        mShakeDetector.registerOnShakeListener(shake);
        checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton arg0, boolean ischecked) {
                // TODO Auto-generated method stub
                if (ischecked) {
                    mShakeDetector.start();

                } else {
                    mShakeDetector.stop();
                }
            }
        });
        checkBox.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (checkBox.isChecked()) {
                    createDialog();
                }
            }
        });
        return view;
    }

    public void createDialog() {
        final Dialog dialog = new Dialog(this.getActivity());
        dialog.setContentView(R.layout.browse_app_list);
        dialog.setTitle("应用列表");
        mlistAppInfo = new ArrayList<AppInfo>();
        queryAppInfo(); // 查询所有应用程序信息
        BrowseApplicationInfoAdapter browseAppAdapter = new BrowseApplicationInfoAdapter(
                this.getActivity(), mlistAppInfo);
        listview.setAdapter(browseAppAdapter);
        listview.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                    int position, long arg3) {
                // TODO Auto-generated method stub
                intent = mlistAppInfo.get(position).getIntent();
            }

        });
        dialog.show();
    }

    public void queryAppInfo() {
        PackageManager pm = this.getActivity().getPackageManager(); // 获得PackageManager对象
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> resolveInfos = pm.queryIntentActivities(mainIntent,
                PackageManager.MATCH_DEFAULT_ONLY);
        Collections.sort(resolveInfos,
                new ResolveInfo.DisplayNameComparator(pm));
        if (mlistAppInfo != null) {
            mlistAppInfo.clear();
            for (ResolveInfo reInfo : resolveInfos) {
                String activityName = reInfo.activityInfo.name; // 获得该应用程序的启动Activity的name
                String pkgName = reInfo.activityInfo.packageName; // 获得应用程序的包名
                String appLabel = (String) reInfo.loadLabel(pm); // 获得应用程序的Label
                Drawable icon = reInfo.loadIcon(pm); // 获得应用程序图标
                // 为应用程序的启动Activity 准备Intent
                Intent launchIntent = new Intent();
                launchIntent.setComponent(new ComponentName(pkgName,
                        activityName));
                // 创建一个AppInfo对象,并赋值
                AppInfo appInfo = new AppInfo();
                appInfo.setAppLabel(appLabel);
                appInfo.setPkgName(pkgName);
                appInfo.setAppIcon(icon);
                appInfo.setIntent(launchIntent);
                mlistAppInfo.add(appInfo); // 添加至列表中
                System.out.println(appLabel + " activityName---" + activityName
                        + " pkgName---" + pkgName);
            }
        }
    }
}

不好意思,解决了,确实是空指针的问题

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Android 中写了一个listview,运行就闪退

一个MainActivity中有三个Fragment(其中有个为MovieFrament),下面这个ViewingFragment是MovieFragment中的一个嵌套的Fragment package com.example.movie; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterViewFlipper; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A simple {@link Fragment} subclass. */ public class ViewingFragment extends Fragment { private ListView listView; private List<Movie2> movieList; private List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>(); public ViewingFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_viewing,container,false); listView = (ListView) view.findViewById(R.id.mov_listview); movieList=initmovies(movieList); for (int i = 0; i < movieList.size(); i++) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("name", movieList.get(i).getName()); map.put("imageId", movieList.get(i).getImageId()); map.put("director", movieList.get(i).getDirector()); map.put("charactors", movieList.get(i).getCharactors()); data.add(map); } SimpleAdapter adapter = new SimpleAdapter(getParentFragment().getActivity(), data, R.layout.movie2_item, new String[]{ "name", "imageId", "director" ,"charactors"}, new int[]{ R.id.txt_name, R.id.imageId, R.id.txt_director, R.id.txt_charactors}); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //我们需要的内容,跳转页面或显示详细信息 Intent intent=new Intent(getActivity(),Mov_InfActivity.class); startActivity(intent); } }); return view; } private static List<Movie2> initmovies(List<Movie2> movieList) { Movie2 apple = new Movie2("悲伤逆流成河", R.mipmap.beishang,"导演:落落","主演:赵英博 任敏 辛云来"); movieList.add(apple); Movie2 banana = new Movie2("新灰姑娘", R.mipmap.huigul,"导演:琳恩.萨瑟兰","主演:Kristen"); movieList.add(banana); Movie2 orange = new Movie2("李茶的姑妈", R.mipmap.licha,"导演:吴昱翰","主演:黄才伦 艾伦 宋阳"); movieList.add(orange); Movie2 watermelon = new Movie2("胖子行动队", R.mipmap.pangzi,"导演:包贝尔 秦小珍","主演:包贝尔 文章 克拉拉"); movieList.add(watermelon); Movie2 pear = new Movie2("无双", R.mipmap.wushuang,"导演:庄文强","主演:周润发 郭富城 张静初"); movieList.add(pear); Movie2 grape = new Movie2("嘻哈英熊", R.mipmap.xiha,"导演:王琦","主演:林强 刘康 徐梦娟"); movieList.add(grape); Movie2 pineapple = new Movie2("影", R.mipmap.ying,"导演:张艺谋","主演:邓超 孙俪 郑恺"); movieList.add(pineapple); Movie2 strawberry = new Movie2("找到你", R.mipmap.zhaodaoni,"导演:吕乐","主演:姚晨 马伊俐 袁文康"); movieList.add(strawberry); return movieList; } }

ListView.setAdapter问题

cannot make a static reference to the non-static method setAdapter(listAdapter) from the type ListVuew![图片](https://img-ask.csdn.net/upload/201511/20/1448020493_479899.jpg)

Fragment使用嵌套listview闪退

import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; public class babyFragment extends Fragment { ListView lv_main;//页面整体list显示 babyViewPagerAdapter babyFramentAdapter; //启动页面 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.a, null); FragmentManager fm = getActivity().getSupportFragmentManager(); babyFramentAdapter = new babyViewPagerAdapter(getActivity(), fm); lv_main = (ListView) v.findViewById(R.id.listview); lv_main.setAdapter(babyFramentAdapter); return v; } } import android.content.*; import android.support.v4.app.*; import android.view.*; import android.widget.*; import kabu.love.zwy.*; public class babyViewPagerAdapter extends BaseAdapter { FragmentManager fm; public babyViewPagerAdapter(Context pContext, FragmentManager fm_tmp) { this.mContext = pContext; fm = fm_tmp; } Context mContext; @Override public int getCount() { return 2; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { LayoutInflater _LayoutInflater = LayoutInflater.from(mContext); switch (i) { case 0: view = _LayoutInflater.inflate( R.layout.mc, viewGroup, false); babyFragment mOneFrament = new babyFragment(); FragmentTransaction babyInfotransaction = fm.beginTransaction(); babyInfotransaction.add(R.id.listview, mOneFrament).commit(); TextView k=(TextView) view.findViewById(R.id.kabu); k.append("k"); break; case 1: view = _LayoutInflater.inflate( R.layout.mc, viewGroup, false); babyFragment mTwoFrament = new babyFragment(); FragmentTransaction feedArchivestransaction = fm.beginTransaction(); feedArchivestransaction.add(R.id.listview, mTwoFrament).commit(); TextView y=(TextView) view.findViewById(R.id.kabu); y.append("y"); break; case 2:// break; case 3:// break; case 4:// break; case 5:// break; } return view; } } 谁帮忙解决一下,打开程序停留1秒闪退,

写了个ListView,打开就崩溃

用的Android Studio。Activity自动在manifests里注册了。 将该activity设置为打开加载页面时,打开就直接闪退。 错误信息一闪就没了... Java代码: package com.demo.listview; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; public class MyLIST extends Activity { private String[] list=getResources().getStringArray(R.array.lesson_name_list_cn); private ListView lv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); lv=(ListView)findViewById(R.id.lv); lv.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,list)); } } XML: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="com.demo.listview"> <!--添加一个ListView控件--> <ListView android:id="@+id/lv" android:layout_width="match_parent" android:layout_height="match_parent"> </ListView> </LinearLayout>

自学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; } } }; }

listview,headerview,listview上的布局 跟随listview一起滑动

我想做一个这样的的布局![图片说明](https://img-ask.csdn.net/upload/201508/04/1438674440_880071.png) 下面是listview,我就是不清楚上面怎么做,如果用headerView 怎么才能实现响应的的点击响应事件! public class MainActivity extends Activity { private ListView lv; private List<String> list; private MyAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initData(); adapter = new MyAdapter(MainActivity.this, list); final View inflate = LayoutInflater.from(getApplicationContext()) .inflate(R.layout.header, null); lv.addHeaderView(inflate, null, false); inflate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Log.d("---->", v.getId() + ""); switch (v.getId()) { case R.id.img1: Toast.makeText(MainActivity.this, "imag1", 0).show(); break; case R.id.img2: Toast.makeText(MainActivity.this, "imag2", 0).show(); break; } } }); lv.setAdapter(adapter); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { if(arg2==0){ inflate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Log.d("---->", v.getId()+""); switch (v.getId()) { case R.id.img1: Toast.makeText(MainActivity.this, "imag1", 0).show(); break; case R.id.img2: Toast.makeText(MainActivity.this, "imag2", 0).show(); break; } } }); } Toast.makeText(MainActivity.this, list.get(arg2), 0).show(); } }); } private void initData() { // TODO Auto-generated method stub lv = (ListView) findViewById(R.id.lv_listview); list = new ArrayList<String>(); for (int i = 0; i < 20; i++) { list.add("this is item" + i); } } 求大神帮忙,最好来代码,!我就是不知道listview上的布局要怎么做(listview上的布局会跟随listview一起滑动的~~!)

Android activity跳转闪退

新手写代码,求大神指导。扫描垃圾页面跳转到清理垃圾页面时闪退 报错信息如下 E/AndroidRuntime: FATAL EXCEPTION: Thread-6 Process: com.itheima.mobilesafe, PID: 19827 java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference at com.itheima.mobilesafe.clean.CleanRubbishActivity$2.run(CleanRubbishActivity.java:125) E/MQSEventManagerDelegate: failed to get MQSService. I/Process: Sending signal. PID: 19827 SIG: 9 Application terminated. 125行是这里 ``` for (RubbishInfo info:mRubbishInfos) ``` 又看了一下,大概是接收数据的时候出现了问题 ``` mRubbishInfos= (List<RubbishInfo>) intent.getSerializableExtra("rubbishInfos"); ``` ![图片说明](https://img-ask.csdn.net/upload/202006/14/1592122391_54904.png) 我搜了一下解决方法有两个,一个是加unchecked注解,这种好像解决不了问题,另外一种是类型检查,但我不知道怎么改,有大神指点吗。

在viewpager和fragment中嵌套listview,出现setAdapter空指针情况。

在viewpager和fragment中嵌套listview,出现setAdapter空指针情况。 为了实现滑动切换界面,我写了三个fragment,在一个fragment中加入了一个listview,怎么启动都是空指针。 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference at com.example.tabhost_02.Fragment_Device.onActivityCreated(Fragment_Device.java:33) at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2619) at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:904) at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238) at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303) at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439) at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079) at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869) at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824) at androidx.fragment.app.FragmentManagerImpl.execSingleAction(FragmentManagerImpl.java:1696) at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:299) at androidx.fragment.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:235) at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1244) at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1092) at androidx.viewpager.widget.ViewPager.onMeasure(ViewPager.java:1622) at android.view.View.measure(View.java:22002) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514) at android.widget.LinearLayout.measureVertical(LinearLayout.java:806) at android.widget.LinearLayout.onMeasure(LinearLayout.java:685) at android.view.View.measure(View.java:22002) at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715) at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461) at android.view.View.measure(View.java:22002) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580) at android.widget.FrameLayout.onMeasure(FrameLayout.java:185) at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143) at android.view.View.measure(View.java:22002) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580) at androidx.appcompat.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:403) at android.view.View.measure(View.java:22002) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580) at android.widget.FrameLayout.onMeasure(FrameLayout.java:185) at android.view.View.measure(View.java:22002) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514) at android.widget.LinearLayout.measureVertical(LinearLayout.java:806) at android.widget.LinearLayout.onMeasure(LinearLayout.java:685) at android.view.View.measure(View.java:22002) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580) at android.widget.FrameLayout.onMeasure(FrameLayout.java:185) at com.android.internal.policy.DecorView.onMeasure(DecorView.java:721) at android.view.View.measure(View.java:22002) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2410) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1498) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1751) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1386) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6733) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911) at android.view.Choreographer.doCallbacks(Choreographer.java:723) at android.view.Choreographer.doFrame(Choreographer.java:658) <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView5" android:layout_width="358dp" android:layout_height="wrap_content" android:text="状态详情" android:textColor="#000000" android:textSize="20sp" android:textStyle="bold" /> <TextView android:id="@+id/textView2" android:layout_width="match_parent" android:layout_height="176dp" android:text="TextView" /> <TextView android:id="@+id/textView3" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="部件信息" android:textColor="#000000" android:textSize="20sp" android:textStyle="bold" /> <TextView android:id="@+id/textView6" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="温度传感器" android:textColor="#2196F3" android:textSize="18sp" android:textStyle="bold" /> <ListView android:id="@+id/lv" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> public class Fragment_Device extends Fragment { private List<Info> infos = new ArrayList<>(); private ListView device_info=null; public Fragment_Device(){ } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_device, container, false); initInfo(); return view; } public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initInfo(); } private void initInfo() { Info dev_1 = new Info("室内环境监控", "20摄氏度", "100小时", "2019-05-01 09:00:00"); infos.add(dev_1); Info dev_2 = new Info("室内环境监控", "25摄氏度", "100小时", "2019-05-01 09:08:00"); infos.add(dev_2); Info dev_3 = new Info("室内环境监控", "23摄氏度", "100小时", "2019-05-01 10:00:00"); infos.add(dev_3); Info dev_4 = new Info("室内环境监控", "28摄氏度", "100小时", "2019-05-01 10:30:00"); infos.add(dev_4); InfoAdapter infoAdapter = new InfoAdapter(infos,getContext()); View view = LayoutInflater.from(getContext()).inflate(R.layout.list_item,null); infos=view.findViewById(R.id.lv); device_info = view.findViewById(R.id.lv); device_info.setAdapter(infoAdapter); } }

fragment中自定义listFragment不显示,程序闪退

fragment中自定义listFragment不显示,程序闪退 这是fragment的代码: package com.example.date4_23; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.Inflater; import android.support.v4.app.ListFragment; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class fragment1 extends ListFragment { private List<Map<String, Object>> data; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment1, container, false); Log.v("huahua", "fragment1-->onCreateView()"); // ViewGroup p = (ViewGroup) mMainView.getParent(); // if (p != null) { // p.removeAllViewsInLayout(); // Log.v("huahua", "fragment1-->移除已存在的View"); // } return v; } @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); data = getDate(); Myadapter adapter = new Myadapter(getActivity()); setListAdapter(adapter); Log.v("huahua", "fragment1-->onCreate()"); } private List<Map<String, Object>> getDate() { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> map = new HashMap<String, Object>(); map.put("img", "img1"); map.put("title", "No.1"); map.put("info", "This is raw No.1"); list.add(map); map = new HashMap<String, Object>(); map.put("img", "img2"); map.put("title", "No.2"); map.put("info", "This is raw No.2"); list.add(map); return list; } static class ViewHolder{ public ImageView img; public TextView title; public TextView info; } public class Myadapter extends BaseAdapter{ private LayoutInflater mInflater = null; private Myadapter(Context context){ this.mInflater = LayoutInflater.from(context); } @Override public int getCount() { // TODO Auto-generated method stub return data.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return data.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { Log.v("getView", "===========================getView================="); ViewHolder holder = null; holder = new ViewHolder(); if(convertView == null) { convertView = mInflater.inflate(R.layout.list_item, null); holder.img = (ImageView)convertView.findViewById(R.id.img); holder.title = (TextView)convertView.findViewById(R.id.title); holder.info = (TextView)convertView.findViewById(R.id.info); convertView.setTag(holder); }else { holder = (ViewHolder)convertView.getTag(); } holder.title.setText((String)data.get(position).get("title")); holder.info.setText((String)data.get(position).get("info")); holder.img.setBackgroundResource((Integer)data.get(position).get("img")); return convertView; } } } 这是布局文件: fragment1.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ffffff" android:orientation="vertical" > <ListView android:id="@+id/android:list" android:layout_width="fill_parent" android:layout_height="wrap_content" > </ListView> </LinearLayout> item的布局: list_item.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ImageView android:id="@+id/img" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" /> <TextView android:id="@+id/info" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14sp" /> </LinearLayout> </LinearLayout> Logcat报错: ![图片说明](https://img-ask.csdn.net/upload/201504/26/1429979468_880634.png) ``` ``` ``` ``` ``` ```

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 Studio中listview与viewpager之间的问题

如何在viewpager中添加listview同时listview的数据是通过网络接口API获取的

在fragment中的listView问题

在fragment中显示一个自定义listView,但是运行后什么也没显示。 public class Tab1 extends Fragment implements ListView.OnItemClickListener{ private ArrayList<Custom> fetch = new ArrayList<Custom>(); private ContactsAdapter adapter; private ListView lv; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){ View v = inflater.inflate(R.layout.tab_layout, container, false); Custom one = new Custom("Hoang Ha", "01672286349"); Custom two = new Custom("Ha Link", "03203590176"); fetch.add(one); fetch.add(two); lv =(ListView)v.findViewById(R.id.list); adapter = new ContactsAdapter(getActivity(), fetch); lv.setAdapter(adapter); lv.setOnItemClickListener(this); return v; } public class Custom{ private String contactName; private String contactPhone; public Custom(String st1, String st2){ contactName = st1; contactPhone = st2; } public String getName(){ return contactName; } public String getPhone(){ return contactPhone; } public void setName(String st1){ contactName = st1; } public void setPhone(String st2){ contactPhone = st2; } } @Override public void onItemClick(AdapterView<?> ad, View v, int position, long id) { // TODO Auto-generated method stub } private class ContactsAdapter extends BaseAdapter{ private FragmentActivity activity; private LayoutInflater inflater; private ArrayList<Custom> data; public ContactsAdapter (FragmentActivity a, ArrayList<Custom> d){ activity = a; data = d; inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // TODO Auto-generated method stub data.size(); return 0; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View v = convertView; v = inflater.inflate(R.layout.list_row, null); TextView contact_name = (TextView)v.findViewById(R.id.contact_name); TextView phone_number = (TextView)v.findViewById(R.id.phone_number); //final Custom custom = entries.get(position); final Custom custom = data.get(position); contact_name.setText(custom.getName()); phone_number.setText(custom.getPhone()); return v; } } } 这是列表xml代码: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:background="@color/light_dark" android:padding="5dip" > <TextView android:id="@+id/contact_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/name" android:textColor="@color/white" android:typeface="sans" android:textSize="@dimen/font_medium" android:textStyle="bold"/> <TextView android:id="@+id/phone_number" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/name" android:textColor="@color/white" android:typeface="sans" android:textSize="@dimen/font_small" /> </LinearLayout>

Android socket通讯客户端连不上服务器问题,以及发送消息程序就闪退

原本以为是线程问题但是好像又不是,实在找不到怎么弄了 这是客户端: package com.chiaki.mysocketobject; import android.content.Intent; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; import java.util.List; public class ChatActivity extends AppCompatActivity implements Runnable{ private static final String HOST = "172.16.2.54"; private static final int PORT = 12345; private MsgAdapter adapter; private ListView msgListView; private List<Msg> msgList=new ArrayList<Msg>(); private ImageButton send; private ImageButton connect; private EditText edit; private TextView ctext; private Socket socket; private BufferedReader in = null; private PrintWriter out = null; private String content = ""; private StringBuilder sb = null; public Handler handler = new Handler() { public void handleMessage(Message msg) { if (msg.what == 0x123) { sb.append(content); ctext.setText(sb.toString()); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); adapter=new MsgAdapter(ChatActivity.this,R.layout.chat_list_view,msgList); ImageButton back = (ImageButton)findViewById(R.id.back); ImageButton voiceButton = (ImageButton)findViewById(R.id.voiceButton); connect = (ImageButton)findViewById(R.id.connectButton); send = (ImageButton)findViewById(R.id.send); edit = (EditText)findViewById(R.id.edit); ctext = (TextView)findViewById(R.id.chattext); msgListView=(ListView)findViewById(R.id.msg_list_view); sb = new StringBuilder(); msgListView.setAdapter(adapter); // 点击按钮实例化Socket对象,与服务端进行连接,获取输入输出流 // 连接服务器,要在子线程中 connect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread() { @Override public void run() { super.run(); try { // 创建socket,连接服务器 socket = new Socket(HOST, PORT);//连接服务器 in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));//接收消息的流对象 out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);//发送消息的流对象 } catch (Exception e) { e.printStackTrace(); } } }.start(); } }); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ChatActivity.this,SocketActivity.class); startActivity(intent); } }); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String con=edit.getText().toString(); edit.setText(""); if (socket.isConnected()) { if (!socket.isOutputShutdown()) { out.println(con);//点击按钮发送消息 } } } }); //启动线程,连接服务器,并用死循环守候,接收服务器发送过来的数据 new Thread(ChatActivity.this).start(); } // 重写run方法,在该方法中输入流的读取 public void run() { try { while (true) { //死循环守护,监控服务器发来的消息 if (socket.isConnected()) { //如果服务器没有关闭 if (!socket.isInputShutdown()) { //连接正常 if ((content = in.readLine()) != null) { //如果输入流没有断开 content += "\n"; //读取接收的信息 handler.sendEmptyMessage(0x123); //会发送一个空消息,但是指定了Message的what属性 } } } } } catch (Exception e) { e.printStackTrace(); } } } 这是layout文件主要的控件: <ImageButton //建立连接按钮 android:layout_width="wrap_content" android:layout_height="wrap_content" app:srcCompat="@android:drawable/checkbox_on_background" android:id="@+id/connectButton" android:layout_alignParentStart="true" android:layout_below="@+id/edit" /> <TextView //显示消息 android:text="TextView" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/chattext" /> <ImageButton //编辑消息 android:layout_width="wrap_content" android:layout_height="wrap_content" app:srcCompat="@android:drawable/ic_btn_speak_now" android:id="@+id/voiceButton" android:layout_below="@+id/edit" android:layout_centerHorizontal="true" /> <ImageButton //发送消息 android:layout_width="wrap_content" android:layout_height="40dp" app:srcCompat="@android:drawable/ic_menu_send" android:id="@+id/send" android:backgroundTint="?attr/colorButtonNormal" android:layout_alignParentBottom="true" android:layout_alignParentEnd="true" /> 这是服务端: import java.io.DataInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class Server { // 定义相关的参数,端口,存储Socket连接的集合,ServerSocket对象 // 以及线程池 private static final int PORT = 12345; private List<Socket> mList = new ArrayList<Socket>(); private ServerSocket server = null; private ExecutorService myExecutorService = null; public static void main(String[] args) { new Server(); } public Server() { try { server = new ServerSocket(PORT); // 创建线程池 myExecutorService = Executors.newCachedThreadPool(); System.out.println("服务端运行中...\n"); Socket client = null; while (true) { client = server.accept(); mList.add(client); myExecutorService.execute(new Service(client)); } } catch (Exception e) { e.printStackTrace(); } } class Service implements Runnable { private Socket socket; private BufferedReader in = null; private String msg = ""; public Service(Socket socket) { this.socket = socket; try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println("用户:" + this.socket.getInetAddress() + "~加入了聊天室" + "当前在线人数:" + mList.size()); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { try { while (true) { if ((msg = in.readLine()) != null) { if (msg.equals("bye")) { System.out.println("~~~~~~~~~~~~~"); mList.remove(socket); in.close(); System.out.println("用户:" + socket.getInetAddress() + "退出:" + "当前在线人数:" + mList.size()); socket.close(); break; } else { System.out.println(socket.getInetAddress() + " 说: " + msg); this.sendmsg(); } } } } catch (Exception e) { e.printStackTrace(); } } // 为连接上服务端的每个客户端发送信息 public void sendmsg() { int num = mList.size(); for (int index = 0; index < num; index++) { Socket mSocket = mList.get(index); PrintWriter pout = null; try { pout = new PrintWriter( new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream(), "UTF-8")), true); pout.println(msg); } catch (IOException e) { e.printStackTrace(); } } } } }

运行到setContentView这里崩溃了

这是第一行代码里面的一个项目,运行后崩溃: ![图片说明](https://img-ask.csdn.net/upload/201702/12/1486848687_748230.jpg) MainActivity.java ``` package com.example.newsapp; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.Window; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); } @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); } } ``` News.java ``` package com.example.newsapp; public class News { private String title; private String content; public String getTitle() { return title; } public void setTitle(String title) { this.title=title; } public String getContent() { return content; } public void setContent(String content) { this.content=content; } } ``` NewsAdapter.java ``` package com.example.newsapp; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class NewsAdapter extends ArrayAdapter<News> { private int resourceId; public NewsAdapter(Context context,int textViewResourceId,List<News> objects) { super(context,textViewResourceId,objects); resourceId=textViewResourceId; } @Override public View getView(int position,View convertView,ViewGroup parent) { News news=getItem(position); View view; if (convertView==null) { view=LayoutInflater.from(getContext()).inflate(resourceId,null); } else { view=convertView; } TextView newsTitleText=(TextView)view.findViewById(R.id.news_title); newsTitleText.setText(news.getTitle()); return view; } } ``` NewsContentActivity.java ``` package com.example.newsapp; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.view.Window; public class NewsContentActivity extends FragmentActivity { public static void actionStart(Context context,String newsTitle,String newsContent) { Intent intent=new Intent(context,NewsContentActivity.class ); intent.putExtra("news_title",newsTitle); intent.putExtra("news_content",newsContent); context.startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.news_content); FragmentManager fragmentManager=getSupportFragmentManager(); String newsTitle=getIntent().getStringExtra("news_title"); String newsContent=getIntent().getStringExtra("news_content"); NewsContentFragment newsContentFragment=(NewsContentFragment)fragmentManager.findFragmentById(R.id.news_content_fragment); newsContentFragment.refresh(newsTitle,newsContent); } } ``` NewsContentFragment.java ``` package com.example.newsapp; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class NewsContentFragment extends Fragment { private View view; @Override public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) { view=inflater.inflate(R.layout.news_content_frag,container,false ); return view; } public void refresh(String newsTitle,String newsContent) { View visibilityLayout=view.findViewById(R.id.visibility_layout); visibilityLayout.setVisibility(View.VISIBLE); TextView newsTitleText=(TextView)view.findViewById(R.id.news_title); TextView newsContentText=(TextView)view.findViewById(R.id.news_content); newsTitleText.setText(newsTitle); newsContentText.setText(newsContent); } } ``` NewsTitleFragment.java ``` package com.example.newsapp; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; public class NewsTitleFragment extends Fragment implements OnItemClickListener { private ListView newsTitleListView; private List<News> newsList; private NewsAdapter adapter; private boolean isTwoPane; @Override public void onAttach(Activity activity) { super.onAttach(activity); newsList=getNews(); adapter=new NewsAdapter(activity,R.layout.news_item,newsList); } @Override public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) { View view=inflater.inflate(R.layout.news_title_frag,container,false ); newsTitleListView=(ListView)view.findViewById(R.id.news_title_list_view); newsTitleListView.setAdapter(adapter); newsTitleListView.setOnItemClickListener(this ); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (getActivity().findViewById(R.id.news_content_layout)!=null ) isTwoPane=true; else isTwoPane=false; } @Override public void onItemClick(AdapterView<?> parent,View view,int position,long id) { News news=newsList.get(position); if (isTwoPane) { NewsContentFragment newsContentFragment=(NewsContentFragment)getFragmentManager().findFragmentById(R.id.news_content_fragment); newsContentFragment.refresh(news.getTitle(),news.getContent()); } else { NewsContentActivity.actionStart(getActivity(),news.getTitle(),news.getContent()); } } private List<News> getNews() { List<News> newsList=new ArrayList<News>(); News news1=new News(); news1.setTitle("标题"); news1.setContent("内容"); newsList.add(news1); News news2=new News(); news2.setTitle("日记"); news2.setContent("去旅游"); newsList.add(news2); return newsList; } } ```

为什么我一调用mAdapter.notifyDataSetChanged();就崩溃

public class MyAdapter extends BaseAdapter { private ArrayList<Item> list; //记录和控制选中状态 private static HashMap<Integer,Boolean> isSelected; //上下文 private Context context; //为子项导入布局 private LayoutInflater inflater; public MyAdapter(ArrayList<Item> list,Context context) { this.list = list; this.context = context; inflater = LayoutInflater.from(context); isSelected = new HashMap<Integer, Boolean>(); //初始化状态 initDate(); } private void initDate() { for(int i=0; i<list.size();i++) { getIsSelected().put(i,false); } } @Override public int getCount() { // TODO Auto-generated method stub return list.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return list.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(final int position, View convertview,ViewGroup parent) { ViewHolder holder ; if(convertview == null) { // 获得ViewHolder对象 holder = new ViewHolder(); // 导入布局并赋值给convertview convertview = inflater.inflate(R.layout.item_layout, null); holder.project_name = (TextView) convertview.findViewById(R.id.project_name); holder.project_result = (TextView) convertview.findViewById(R.id.project_result); holder.project_resultval = (TextView) convertview.findViewById(R.id.project_resultval); holder.cbox = (CheckBox) convertview.findViewById(R.id.box); holder.cbox.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (isSelected.get(position)) { isSelected.put(position, false); setIsSelected(isSelected); } else { isSelected.put(position, true); setIsSelected(isSelected); } } }); // 为view设置标签 convertview.setTag(holder); } else { holder = (ViewHolder) convertview.getTag(); } holder.project_name.setText(list.get(position).getproject_name()); holder.project_result.setText(list.get(position).getproject_result()); holder.project_resultval.setText(list.get(position).getproject_resultval()); // 根据isSelected来设置checkbox的选中状况 holder.cbox.setChecked(getIsSelected().get(position)); return convertview; } public static HashMap<Integer,Boolean> getIsSelected() { return isSelected; } public static void setIsSelected(HashMap<Integer,Boolean> isSelected) { MyAdapter.isSelected = isSelected; } public final class ViewHolder { public TextView project_name; public TextView project_result; public TextView project_resultval; public CheckBox cbox; } }

android popupwindow dismiss()关闭窗体前的处理事件

pop.setTouchable(true); pop.setBackgroundDrawable(new BitmapDrawable()); // 上面两句代码当点击窗体外部popupwindow自动消失 我想让popupwindow消失前执行一段代码,比如改变字体等,那么如何重写dismiss()方法啊? 贴出部分源码 public void popup() {// inflater = (LayoutInflater)popupTest.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View listLayout = inflater.inflate(R.layout.listview, null); listView= (ListView) listLayout.findViewById(android.R.id.list); lvButtonAdapter listItemAdapter = new lvButtonAdapter(this,list1, R.layout.item, new String[]{"text1","text2","ItemImage,RelativeLayout"}, new int[]{R.id.text1,R.id.text2,R.id.pup,R.id.re}); listView.setAdapter(listItemAdapter); listView.setFocusable(true); listView.setItemsCanFocus(true); listView.setOnItemClickListener(new OnItemClickListener(){public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) { edit1.getText().insert (edit1.getSelectionStart(),list1.get(arg2).get("text1").toString()); pop.dismiss(); }});//光标处插入文字 pop = new PopupWindow(listLayout, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); pop.setTouchable(true); pop.setBackgroundDrawable(new BitmapDrawable()); // pop.setFocusable(true); }

android 当在主线程里开启一个新线程 程序就崩溃

我要实现的功能是检索SDcard里的所有txt文件 我尝试过很多办法 1 不用线程 直接在主线程里检索文件 由于有循环且检索时间会超过5秒 导致黑屏然后提示未响应 2 我建立一个线程让线程去检索文件当检索完毕后把检索到的文件传递给主类 主类再把检索到的文件显示在list上 但是当线程一启动程序就崩溃了 3 最后我在主类里添加handler 当子线程检索完毕就sendmessage给主类 然后主类把子线程检索到的文件显示在list上但程序还是崩溃 我没在子线程里操作UI 好像只要子线程里有循环程序就会崩溃 下面我把代码贴出来希望大家能帮帮我解决下这个问题 主类的主要代码 enter code here int jishuqi = 0; ProgressDialog progress; jiansuothread thread; Intent intent; int[] leixing_xuanzhe; FileReader file; File fuwenjian; File fuwenjianxia[]; String[] leixing = new String[] {"doc","pdf","xls","txt","jpg","ppt"}; int i = 0; ArrayList<File[]>root = new ArrayList<File[]>(); String xuanxiang [] = new String [] {"向上","编辑","添加","删除"}; int ico [] = new int[] {R.drawable.xinjian,R.drawable.xinjian,R.drawable.xinjian,R.drawable.xinjian}; ListView list; Button xiangshang; Button bianji; Button tianjia; Button shanchu; View v; static ArrayList<File[]>jiansuoroot = new ArrayList<File[]>(); static List<File>jiansuowenjian = new ArrayList<File>(); static File fi; static ArrayList<File>wenjianjia = new ArrayList<File>(); static ArrayList<File>ziwenjian = new ArrayList<File>(); static ArrayList<File[]>ziwenjian1 = new ArrayList<File[]>(); static ArrayList<File[]>rootwenjianjia = new ArrayList<File[]>(); //jiansuowen js = new jiansuowen(); //zixiancheng xiancheng = null; Handler hanlder; Handler handler = null; Handler childhandler = null; boolean jiansuowanbi = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_text); xiancheng = new zixiancheng(); xiancheng.start(); v = (View)findViewById(R.id.view1); intent = this.getIntent(); leixing_xuanzhe = intent.getIntArrayExtra("leixing_xuanzhe"); list = (ListView)findViewById(R.id.fileslist); parse(leixing_xuanzhe); list.setOnItemClickListener(new mylistitemclick()); xiangshang = (Button)findViewById(R.id.wj_xiangshang); bianji = (Button)findViewById(R.id.wj_bianji); tianjia = (Button)findViewById(R.id.wj_tianjia); shanchu = (Button)findViewById(R.id.wj_shanchu); xiangshang.setOnClickListener(new myClick()); bianji.setOnClickListener(new myClick()); tianjia.setOnClickListener(new myClick()); shanchu.setOnClickListener(new myClick()); //thread = new jiansuothread(this); handler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub if(msg.what == 111) { progress.cancel(); List<Map<String,Object>>listitems = new ArrayList<Map<String,Object>>(); for(int i= 0;i<jiansuowenjian.size();i++) { Map<String,Object>item = new HashMap<String,Object>(); item.put("icon",R.drawable.file ); item.put("name", jiansuowenjian.get(i).getName()); listitems.add(item); } SimpleAdapter adpter = new SimpleAdapter(TexlisttActivity.this,listitems , R.layout.list, new String[] {"icon","name"}, new int[] {R.id.icon,R.id.listitem}); list.setAdapter(adpter); } } }; }` 子线程的代码 enter code here` class zixiancheng extends Thread { Message msg = null; public void run() { Looper.prepare(); childhandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub if(msg.what == 222) { try { for(int i =0; i<wenjianjia.size();i++) { jinasuo1(wenjianjia.get(i)); } jiansuowanbi = true; msg = handler.obtainMessage(); msg.what = 111; handler.sendMessage(msg); } catch (Exception e) { // TODO: handle exception } } } }; Looper.loop(); } }

《第一行代码》的酷欧天气,点开省列表以后显示的还是省,而不是城市,这是再点一下省就直接闪退

Logcat如下 FATAL EXCEPTION: main Process: com.coolweather.android, PID: 11807 java.lang.IndexOutOfBoundsException: Index: 6, Size: 0 at java.util.ArrayList.get(ArrayList.java:411) at com.coolweather.android.ChooseAreaFragment$1.onItemClick(ChooseAreaFragment.java:76) at android.widget.AdapterView.performItemClick(AdapterView.java:310) at android.widget.AbsListView.performItemClick(AbsListView.java:1165) at android.widget.AbsListView$PerformClick.run(AbsListView.java:3137) at android.widget.AbsListView$3.run(AbsListView.java:4052) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6290) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 代码如下 package com.coolweather.android; import android.app.ProgressDialog; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.coolweather.android.db.City; import com.coolweather.android.db.County; import com.coolweather.android.db.Province; import com.coolweather.android.util.HttpUtil; import com.coolweather.android.util.Utility; import org.litepal.crud.DataSupport; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * Created by 王耀祖 on 2017/7/20. */ public class ChooseAreaFragment extends Fragment { public static final int LEVEL_PROVINCE = 0; public static final int LEVEL_CITY = 1; public static final int LEVEL_COUNTY = 2; private ProgressDialog progressDialog; private TextView titleText; private Button backButton; private ListView listView; private ArrayAdapter<String> adapter; private List<String> dataList = new ArrayList<>(); private List<Province> provinceList; private List<City> cityList; private List<County> countyList; private Province selectedProvince; private City selectedCity; private int currentLevel; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.choose_area, container, false); titleText = (TextView) view.findViewById(R.id.title_text); backButton = (Button) view.findViewById(R.id.back_button); listView = (ListView) view.findViewById(R.id.list_view); adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, dataList); listView.setAdapter(adapter); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (currentLevel == LEVEL_PROVINCE) { selectedProvince = provinceList.get(position); queryCities(); } else if (currentLevel == LEVEL_CITY) { selectedCity = cityList.get(position); queryCounties(); } } }); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(currentLevel==LEVEL_COUNTY){ queryCities(); } else if(currentLevel==LEVEL_CITY){ queryProvinces(); } } }); queryProvinces(); } private void queryProvinces(){ titleText.setText("中国"); backButton.setVisibility(View.GONE); provinceList= DataSupport.findAll(Province.class); if(provinceList.size()>0){ dataList.clear(); for(Province province:provinceList) dataList.add(province.getProvinceName()); adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel=LEVEL_PROVINCE; } else{ String address="http://guolin.tech/api/china"; queryFromServer(address,"province"); } } private void queryCities(){ titleText.setText(selectedProvince.getProvinceName()); backButton.setVisibility(View.VISIBLE); cityList=DataSupport.where("provinceid = ?",String.valueOf(selectedProvince .getId())).find(City.class); if(cityList.size()>0) { cityList.clear(); for(City city:cityList) dataList.add(city.getCityName()); adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel=LEVEL_CITY; } else{ int provinceCode=selectedProvince.getProvinceCode(); String address="http://guolin.tech/api/china/"+provinceCode; queryFromServer(address,"city"); } } private void queryCounties(){ titleText.setText(selectedCity.getCityName()); backButton.setVisibility(View.VISIBLE); countyList=DataSupport.where("cityid = ?",String.valueOf(selectedCity .getId())).find(County.class); if(countyList.size()>0) { countyList.clear(); for(County county:countyList) dataList.add(county.getCountyName()); adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel=LEVEL_COUNTY; } else{ int provinceCode=selectedProvince.getProvinceCode(); int cityCode=selectedCity.getCityCode(); String address="http://guolin.tech/api/china/"+provinceCode+"/"+cityCode; queryFromServer(address,"county"); } } private void queryFromServer(String address,final String type){ showProgressDialog(); HttpUtil.sendOkHttpRequest(address, new Callback() { @Override public void onFailure(Call call, IOException e) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String responseText=response.body().string(); boolean result=false; if("province".equals(type)) result= Utility.handleProvinceResponse(responseText); else if("city".equals(type)) result=Utility.handleCityResponse(responseText,selectedProvince.getId()); else if("county".equals(type)) result=Utility.handleCountyResponse(responseText,selectedCity.getId()); if(result){ getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); if("province".equals(type)) queryProvinces(); else if("city".equals(type)) queryCities(); else if("county".equals(type)) queryCounties(); } }); } } }); } private void showProgressDialog(){ if(progressDialog==null){ progressDialog=new ProgressDialog(getActivity()); progressDialog.setMessage("正在加载。。。"); progressDialog.setCanceledOnTouchOutside(false); } progressDialog.show(); } private void closeProgressDialog(){ if(progressDialog!=null) progressDialog.dismiss(); } }

当旋转Android屏幕时App自动加载数据

我打开我的应用时数据会自动加载, 我的问题是:当屏幕是垂直的时候应用会从服务器上加载下数据,但当屏幕旋转的时候,它又重新加载数据,在垂直状态又重新加载,旋转也是,一直如此。我应该怎么做才能让它不重新加载数据,希望大家能帮我看看,应该如何处理。 程序代码如下: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.nhabep); new LoadData().execute(); } // Class load data private class LoadData extends AsyncTask<Void, Void, Void> { private ProgressDialog progressDialog; private JSONArray jArray; private String result = null; private InputStream is = null; private StringBuilder sb = null; @Override protected void onPreExecute() { this.progressDialog = ProgressDialog.show(Nhabep.this, "", " Loading..."); } @Override protected void onPostExecute(final Void unused) { this.progressDialog.dismiss(); try { if (flag == false) { Toast.makeText(Nhabep.this, "欢迎使用!!", Toast.LENGTH_SHORT).show(); } else { // listview listview = (ListView) findViewById(R.id.listView1); this.progressDialog.dismiss(); listview.setAdapter(new DataAdapter(Nhabep.this, soban .toArray(new String[soban.size()]), thoigian .toArray(new String[thoigian.size()]))); listview.setOnItemClickListener(new OnItemClickListener() { // listview @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub String soban2 = soban.get(position); String cafesua2 = cafesua.get(position); String cafeda2 = cafeda.get(position); String cafeden2 = cafeden.get(position); String duatuoi2 = duatuoi.get(position); String nuocngot2 = nuocngot.get(position); String cavienchien2 = cavienchien.get(position); String goiga2 = goiga.get(position); String bokho2 = bokho.get(position); String bunbo2 = bunbo.get(position); Intent i = new Intent(Nhabep.this, Show.class); i.putExtra("soban", soban2); i.putExtra("cafesua", cafesua2); i.putExtra("cafeda", cafeda2); i.putExtra("cafeden", cafeden2); i.putExtra("duatuoi", duatuoi2); i.putExtra("nuocngot", nuocngot2); i.putExtra("cavienchien", cavienchien2); i.putExtra("goiga", goiga2); i.putExtra("bokho", bokho2); i.putExtra("bunbo", bunbo2); startActivity(i); } }); Toast.makeText(Nhabep.this, "欢迎使用!!", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show(); } } // server @Override protected Void doInBackground(Void... params) { try { ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( "http://longvansolution.tk/loadthongtin.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); BufferedReader reader = new BufferedReader( new InputStreamReader(is, "iso-8859-1"), 80); sb = new StringBuilder(); sb.append(reader.readLine() + "\n"); String line = "0"; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); if (result.toString().equalsIgnoreCase("null\n")) { flag = false; soban.clear(); thoigian.clear(); cafesua.clear(); cafeda.clear(); cafeden.clear(); duatuoi.clear(); nuocngot.clear(); cavienchien.clear(); goiga.clear(); bokho.clear(); bunbo.clear(); } else { // tin theo Json jArray = new JSONArray(result); if (jArray != null && jArray.length() > 0) { JSONObject json_data = null; soban.clear(); thoigian.clear(); cafesua.clear(); cafeda.clear(); cafeden.clear(); duatuoi.clear(); nuocngot.clear(); cavienchien.clear(); goiga.clear(); bokho.clear(); bunbo.clear(); for (int i = 0; i < jArray.length(); i++) { json_data = jArray.getJSONObject(i); thoigian1 = json_data.getString("date"); soban1 = json_data.getString("ban"); cafesua1 = json_data.getString("cafesua"); cafeda1 = json_data.getString("cafeda"); cafeden1 = json_data.getString("cafeden"); duatuoi1 = json_data.getString("duatuoi"); nuocngot1 = json_data.getString("nuocngot"); cavienchien1 = json_data.getString("cavienchien"); goiga1 = json_data.getString("goiga"); bokho1 = json_data.getString("bokho"); bunbo1 = json_data.getString("bunbo"); thoigian.add(thoigian1); soban.add(soban1); cafesua.add(cafesua1); cafeden.add(cafeden1); cafeda.add(cafeda1); duatuoi.add(duatuoi1); nuocngot.add(nuocngot1); cavienchien.add(cavienchien1); goiga.add(goiga1); bokho.add(bokho1); bunbo.add(bunbo1); } } flag = true; } } catch (Exception e) { // Log.e("log_tag", "Error in http connection" + e.toString()); Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show(); } return null; } }

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

Vue + Spring Boot 项目实战(十九):Web 项目优化解决方案

快来一起探索如何打脸我们的破项目,兄弟姐妹们把害怕打在公屏上!

你连存活到JDK8中著名的Bug都不知道,我怎么敢给你加薪

CopyOnWriteArrayList.java和ArrayList.java,这2个类的构造函数,注释中有一句话 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public ArrayList(Collection&lt;? ...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

CSDN:因博主近期注重写专栏文章(已超过150篇),订阅博主专栏人数在突增,近期很有可能提高专栏价格(已订阅的不受影响),提前声明,敬请理解!

CSDN:因博主近期注重写专栏文章(已超过150篇),订阅博主专栏人数在突增,近期很有可能提高专栏价格(已订阅的不受影响),提前声明,敬请理解! 目录 博客声明 大数据了解博主粉丝 博主的粉丝群体画像 粉丝群体性别比例、年龄分布 粉丝群体学历分布、职业分布、行业分布 国内、国外粉丝群体地域分布 博主的近期访问每日增量、粉丝每日增量 博客声明 因近期博主写专栏的文章越来越多,也越来越精细,逐步优化文章。因此,最近一段时间,订阅博主专栏的人数增长也非常快,并且专栏价

一个HashMap跟面试官扯了半个小时

一个HashMap能跟面试官扯上半个小时 关注 安琪拉的博客 1.回复面试领取面试资料 2.回复书籍领取技术电子书 3.回复交流领取技术电子书 前言 HashMap应该算是Java后端工程师面试的必问题,因为其中的知识点太多,很适合用来考察面试者的Java基础。 开场 面试官: 你先自我介绍一下吧! 安琪拉: 我是安琪拉,草丛三婊之一,最强中单(钟馗不服)!哦,不对,串场了,我是**,目...

我说我不会算法,阿里把我挂了。

不说了,字节跳动也反手把我挂了。

记录下入职中软一个月(外包华为)

我在年前从上一家公司离职,没想到过年期间疫情爆发,我也被困在家里,在家呆着的日子让人很焦躁,于是我疯狂的投简历,看面试题,希望可以进大公司去看看。 我也有幸面试了我觉得还挺大的公司的(虽然不是bat之类的大厂,但是作为一名二本计算机专业刚毕业的大学生bat那些大厂我连投简历的勇气都没有),最后选择了中软,我知道这是一家外包公司,待遇各方面甚至不如我的上一家公司,但是对我而言这可是外包华为,能...

面试:第十六章:Java中级开发

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

培训班出来的人后来都怎么样了?(二)

接着上回说,培训班学习生涯结束了。后面每天就是无休止的背面试题,不是没有头脑的背,培训公司还是有方法的,现在回想当时背的面试题好像都用上了,也被问到了。回头找找面试题,当时都是打印下来天天看,天天背。 不理解呢也要背,面试造飞机,上班拧螺丝。班里的同学开始四处投简历面试了,很快就有面试成功的,刚开始一个,然后越来越多。不知道是什么原因,尝到胜利果实的童鞋,不满足于自己通过的公司,嫌薪水要少了,选择...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

工作八年,月薪60K,裸辞两个月,投简历投到怀疑人生!

近日,有网友在某职场社交平台吐槽,自己裸辞两个月了,但是找工作却让自己的心态都要崩溃了,全部无果,不是已查看无回音,就是已查看不符合。 “工作八年,两年一跳,裸辞两个月了,之前月薪60K,最近找工作找的心态崩了!所有招聘工具都用了,全部无果,不是已查看无回音,就是已查看不符合。进头条,滴滴之类的大厂很难吗???!!!投简历投的开始怀疑人生了!希望 可以收到大厂offer” 先来看看网...

大牛都会用的IDEA调试技巧!!!

导读 前天面试了一个985高校的实习生,问了他平时用什么开发工具,他想也没想的说IDEA,于是我抛砖引玉的问了一下IDEA的调试用过吧,你说说怎么设置断点...

都前后端分离了,咱就别做页面跳转了!统统 JSON 交互

文章目录1. 无状态登录1.1 什么是有状态1.2 什么是无状态1.3 如何实现无状态1.4 各自优缺点2. 登录交互2.1 前后端分离的数据交互2.2 登录成功2.3 登录失败3. 未认证处理方案4. 注销登录 这是本系列的第四篇,有小伙伴找不到之前文章,松哥给大家列一个索引出来: 挖一个大坑,Spring Security 开搞! 松哥手把手带你入门 Spring Security,别再问密...

97年世界黑客编程大赛冠军作品(大小仅为16KB),惊艳世界的编程巨作

这是世界编程大赛第一名作品(97年Mekka ’97 4K Intro比赛)汇编语言所写。 整个文件只有4095个字节, 大小仅仅为16KB! 不仅实现了3D动画的效果!还有一段震撼人心的背景音乐!!! 内容无法以言语形容,实在太强大! 下面是代码,具体操作看最后! @echo off more +1 %~s0|debug e100 33 f6 bf 0 20 b5 10 f3 a5...

程序员是做全栈工程师好?还是专注一个领域好?

昨天,有位大一的同学私信我,说他要做全栈工程师。 我一听,这不害了孩子么,必须制止啊。 谁知,讲到最后,更确定了他做全栈程序员的梦想。 但凡做全栈工程师的,要么很惨,要么很牛! 但凡很牛的,绝不是一开始就是做全栈的! 全栈工程师听起来好听,但绝没有你想象的那么简单。 今天听我来给你唠,记得帮我点赞哦。 一、全栈工程师的职责 如果你学习编程的目的只是玩玩,那随意,想怎么学怎么学。...

不要再到处使用 === 了

我们知道现在的开发人员都使用 === 来代替 ==,为什么呢?我在网上看到的大多数教程都认为,要预测 JavaScript 强制转换是如何工作这太复杂了,因此建议总是使用===。这些都...

什么是a站、b站、c站、d站、e站、f站、g站、h站、i站、j站、k站、l站、m站、n站?00后的世界我不懂!

A站 AcFun弹幕视频网,简称“A站”,成立于2007年6月,取意于Anime Comic Fun,是中国大陆第一家弹幕视频网站。A站以视频为载体,逐步发展出基于原生内容二次创作的完整生态,拥有高质量互动弹幕,是中国弹幕文化的发源地;拥有大量超粘性的用户群体,产生输出了金坷垃、鬼畜全明星、我的滑板鞋、小苹果等大量网络流行文化,也是中国二次元文化的发源地。 B站 全称“哔哩哔哩(bilibili...

十个摸鱼,哦,不对,是炫酷(可以玩一整天)的网站!!!

文章目录前言正文**1、Kaspersky Cyberthreat real-time map****2、Finding Home****3、Silk – Interactive Generative Art****4、Liquid Particles 3D****5、WINDOWS93****6、Staggering Beauty****7、Ostagram图片生成器网址****8、全历史网址*...

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

用了这个 IDE 插件,5分钟解决前后端联调!

点击上方蓝色“程序猿DD”,选择“设为星标”回复“资源”获取独家整理的学习资料!作者 |李海庆我是一个 Web 开发前端工程师,受到疫情影响,今天是我在家办公的第78天。开发了两周,...

大厂的 404 页面都长啥样?最后一个笑了...

每天浏览各大网站,难免会碰到404页面啊。你注意过404页面么?猿妹搜罗来了下面这些知名网站的404页面,以供大家欣赏,看看哪个网站更有创意: 正在上传…重新上传取消 腾讯 正在上传…重新上传取消 网易 淘宝 百度 新浪微博 正在上传…重新上传取消 新浪 京东 优酷 腾讯视频 搜...

自从喜欢上了B站这12个UP主,我越来越觉得自己是个废柴了!

不怕告诉你,我自从喜欢上了这12个UP主,哔哩哔哩成为了我手机上最耗电的软件,几乎每天都会看,可是吧,看的越多,我就越觉得自己是个废柴,唉,老天不公啊,不信你看看…… 间接性踌躇满志,持续性混吃等死,都是因为你们……但是,自己的学习力在慢慢变强,这是不容忽视的,推荐给你们! 都说B站是个宝,可是有人不会挖啊,没事,今天咱挖好的送你一箩筐,首先啊,我在B站上最喜欢看这个家伙的视频了,为啥 ,咱撇...

代码注释如此沙雕,会玩还是你们程序员!

某站后端代码被“开源”,同时刷遍全网的,还有代码里的那些神注释。 我们这才知道,原来程序员个个都是段子手;这么多年来,我们也走过了他们的无数套路… 首先,产品经理,是永远永远吐槽不完的!网友的评论也非常扎心,说看这些代码就像在阅读程序员的日记,每一页都写满了对产品经理的恨。 然后,也要发出直击灵魂的质问:你是尊贵的付费大会员吗? 这不禁让人想起之前某音乐app的穷逼Vip,果然,穷逼在哪里都是...

Java14 新特性解读

Java14 已于 2020 年 3 月 17 号发布,官方特性解读在这里:https://openjdk.java.net/projects/jdk/14/以下是个人对于特性的中文式...

前端还能这么玩?(女朋友生日,用前端写了一个好玩的送给了她,高兴坏了)

前端还能这么玩?(女朋友生日,用前端写了一个好玩的送给了她,高兴坏了)

爬虫(101)爬点重口味的

小弟最近在学校无聊的很哪,浏览网页突然看到一张图片,都快流鼻血。。。然后小弟冥思苦想,得干一点有趣的事情python 爬虫库安装https://s.taobao.com/api?_ks...

工作两年简历写成这样,谁要你呀!

作者:小傅哥 博客:https://bugstack.cn 沉淀、分享、成长,让自己和他人都能有所收获! 一、前言 最近有伙伴问小傅哥,我的简历怎么投递了都没有反应,心里慌的很呀。 工作两年了目前的公司没有什么大项目,整天的维护别人的代码,有坑也不让重构,都烦死了。荒废我一身技能无处施展,投递的简历也没人看。我是不动物园里的猩猩,狒狒了! 我要加班,我要996,我要疯狂编码,求给我个机会… ...

相关热词 c# 局部 截图 页面 c#实现简单的文件管理器 c# where c# 取文件夹路径 c# 对比 当天 c# fir 滤波器 c# 和站 队列 c# txt 去空格 c#移除其他类事件 c# 自动截屏
立即提问