安卓编程问题1

今天突发奇想做了一个安卓界面的实验。实验的大体思想如下。
1在mainActivity的layout中添加一个button1
2在secondActivity的onCreate中添加一个代码。

Button button =(Button) findViewById(R.id.button1);
        button.setText("dddddddddd");

然后在启动主程序

实验结果如下:
主程序启动没有任何异常。但是在按钮调用secondActiviey的时候出现程序崩溃。
得到的错误代码如下

07-14 12:19:30.507    6882-6907/com.example.bleuesprit.test W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb431bc40, error=EGL_SUCCESS

07-14 12:19:54.503    6882-6882/com.example.bleuesprit.test D/AndroidRuntime﹕ Shutting down VM
07-14 12:19:54.504    6882-6882/com.example.bleuesprit.test E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.bleuesprit.test, PID: 6882
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bleuesprit.test/com.example.bleuesprit.test.secondActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setText(java.lang.CharSequence)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setText(java.lang.CharSequence)' on a null object reference
            at com.example.bleuesprit.test.secondActivity.onCreate(secondActivity.java:20)
            at android.app.Activity.performCreate(Activity.java:5990)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
07-14 12:19:54.550    6882-6895/com.example.bleuesprit.test I/art﹕ WaitForGcToComplete blocked for 45.527ms for cause Background
07-14 12:19:54.807    6882-6890/com.example.bleuesprit.test W/art﹕ Suspending all threads took: 30.132ms
07-14 12:19:55.006    6882-6895/com.example.bleuesprit.test I/art﹕ Background partial concurrent mark sweep GC freed 881(96KB) AllocSpace objects, 0(0B) LOS objects, 50% free, 995KB/2019KB, paused 183.236ms total 450.860ms
07-14 12:19:55.046    6882-6895/com.example.bleuesprit.test W/art﹕ Suspending all threads took: 40.097ms

关键的信息就是一行

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bleuesprit.test/com.example.bleuesprit.test.secondActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setText(java.lang.CharSequence)' on a null object reference

空指针异常。原因是button是个空指针。所以setText的时候出现错误。
原因:
我估计在secondActivity的时候。之前的layout已经释放资源,或者secondActivity并不能看得到。这样button是一个空指针。

正确做法。
1mainActivity调用startActivityForResult函数来调取secondActivity

Intent intent =new      Intent(MainActiveity.this,secondActivity.class);

startActivityForResult(intent, 1);

2secondActivity 调用setResult设置返回的intend,其中dddddd可以放在这个结果intend中。调用finish()结束

Intent intent = new Intent();
intent.putExtra("buttonText", "ddddddd");
setResult(RESULT_OK, intent);
finish();

3mainActivity重写onActivityResult来进行更改操作

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    Button button =(Button)findViewById(R.id.button1);
                    String text=getIntent().getStringExtra("buttonText");
                    button.setText(text);
                }
                break;
            default:
        }
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是使用Android Studio实现访问接口获取数据、解析并显示到界面的控件上、将数据保存到本地SQLite数据库中的步骤: 1. 在Android Studio中创建一个新项目(可以选择空白模板),并在`build.gradle`文件中添加以下依赖项: ```gradle dependencies { implementation 'com.android.volley:volley:1.1.1' } ``` 这里我们使用Volley库来进行网络请求。 2. 创建一个布局文件`activity_main.xml`,在其中添加一个ListView控件,用于显示获取到的数据。 ```xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout> ``` 3. 创建一个数据模型类`NewsItem.java`,用于存储获取到的新闻数据。 ```java public class NewsItem { private int id; private String title; private String detail; private int comment; private String image; public NewsItem(int id, String title, String detail, int comment, String image) { this.id = id; this.title = title; this.detail = detail; this.comment = comment; this.image = image; } public int getId() { return id; } public String getTitle() { return title; } public String getDetail() { return detail; } public int getComment() { return comment; } public String getImage() { return image; } } ``` 4. 创建一个适配器类`NewsAdapter.java`,用于将获取到的新闻数据显示到ListView控件上。 ```java public class NewsAdapter extends ArrayAdapter<NewsItem> { private int resourceId; public NewsAdapter(Context context, int resourceId, List<NewsItem> objects) { super(context, resourceId, objects); this.resourceId = resourceId; } @Override public View getView(int position, View convertView, ViewGroup parent) { NewsItem item = getItem(position); View view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false); TextView titleView = view.findViewById(R.id.title_view); TextView detailView = view.findViewById(R.id.detail_view); titleView.setText(item.getTitle()); detailView.setText(item.getDetail()); return view; } } ``` 这里我们使用了自定义的布局文件`list_item.xml`,用于定义ListView中每个Item的样式。 ```xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="16dp"> <TextView android:id="@+id/title_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="18sp" android:textStyle="bold"/> <TextView android:id="@+id/detail_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="14sp"/> </LinearLayout> ``` 5. 在MainActivity中发起网络请求,获取数据并解析,将数据显示到ListView控件上,并将数据保存到本地SQLite数据库中。 ```java public class MainActivity extends AppCompatActivity { private List<NewsItem> newsList = new ArrayList<>(); private NewsAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listView = findViewById(R.id.list_view); adapter = new NewsAdapter(this, R.layout.list_item, newsList); listView.setAdapter(adapter); // 发起网络请求,获取数据 String url = "http://192.168.1.100:8080/news/getnewslist"; JsonObjectRequest request = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONArray jsonArray = response.getJSONArray("data"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); int id = jsonObject.getInt("id"); String title = jsonObject.getString("title"); String detail = jsonObject.getString("detail"); int comment = jsonObject.getInt("comment"); String image = jsonObject.getString("image"); NewsItem item = new NewsItem(id, title, detail, comment, image); newsList.add(item); } adapter.notifyDataSetChanged(); // 将数据保存到本地SQLite数据库中 SQLiteDatabase db = openOrCreateDatabase("news.db", MODE_PRIVATE, null); db.execSQL("CREATE TABLE IF NOT EXISTS news (id INTEGER PRIMARY KEY, title TEXT, detail TEXT, comment INTEGER, image TEXT)"); for (NewsItem item : newsList) { db.execSQL("INSERT INTO news (id, title, detail, comment, image) VALUES (?, ?, ?, ?, ?)", new Object[]{item.getId(), item.getTitle(), item.getDetail(), item.getComment(), item.getImage()}); } db.close(); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); Volley.newRequestQueue(this).add(request); } } ``` 这样,我们就完成了使用Android Studio实现访问接口获取数据、解析并显示到界面的控件上、将数据保存到本地SQLite数据库中的整个过程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值