簡體   English   中英

如何從簡單列表視圖的按鈕打開新活動

[英]How to open new activity from button of simple list view

開發人員我遇到了一個嚴重的問題我有一個簡單的列表視圖,它有一個圖像視圖和幾個文本視圖來顯示一些文本和兩個按鈕。 現在的問題是,當我在按鈕上設置單擊偵聽器時發生空指針錯誤。 我在谷歌上搜索了這個問題並找到了一個解決方案來制作自定義適配器來解決這個問題,但我不想使用自定義適配器有沒有辦法在我的代碼下面沒有自定義適配器類的情況下解決這個問題:

 public class JsonParsing extends AppCompatActivity { Button det; Button trans; private String TAG = MainActivity.class.getSimpleName(); private ListView lv; ArrayList<HashMap<String, String>> contactList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_json_parsing); det = (Button) findViewById(R.id.det); trans = (Button) findViewById(R.id.trans); // trans.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Intent intent = new Intent(JsonParsing.this, MainActivity.class); // startActivity(intent); // } // }); contactList = new ArrayList<>(); lv = (ListView) findViewById(R.id.list); new GetContacts().execute(); } private class GetContacts extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); Toast.makeText(JsonParsing.this,"Json Data is downloading",Toast.LENGTH_LONG).show(); } @Override protected Void doInBackground(Void... arg0) { HttpHandler sh = new HttpHandler(); // Making a request to url and getting response String url = "https://api.androidhive.info/contacts/"; String jsonStr = sh.makeServiceCall(url); Log.e(TAG, "Response from url: " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); // Getting JSON Array node JSONArray contacts = jsonObj.getJSONArray("contacts"); // looping through All Contacts for (int i = 0; i < contacts.length(); i++) { JSONObject c = contacts.getJSONObject(i); String id = c.getString("id"); String name = c.getString("name"); String email = c.getString("email"); String address = c.getString("address"); String gender = c.getString("gender"); // Phone node is JSON Object JSONObject phone = c.getJSONObject("phone"); String mobile = phone.getString("mobile"); String home = phone.getString("home"); String office = phone.getString("office"); // tmp hash map for single contact HashMap<String, String> contact = new HashMap<>(); // adding each child node to HashMap key => value contact.put("id", id); contact.put("name", name); contact.put("email", email); contact.put("mobile", mobile); contact.put("address", address); contact.put("gender", gender); // adding contact to contact list contactList.add(contact); } } catch (final JSONException e) { Log.e(TAG, "Json parsing error: " + e.getMessage()); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } }); } } else { Log.e(TAG, "Couldn't get json from server."); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG).show(); } }); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); ListAdapter adapter = new SimpleAdapter(JsonParsing.this, contactList, R.layout.list_item, new String[]{"id", "name","email","mobile","address","gender"}, new int[]{R.id.id,R.id.name,R.id.email, R.id.mobile,R.id.address,R.id.gender}); lv.setAdapter(adapter); } } }

XML文件:

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/colorPrimaryDark"> <ImageView android:id="@+id/icon" android:layout_width="80dp" android:layout_height="80dp" android:background="@drawable/car" android:layout_marginTop="25dp" android:paddingLeft="10dp" android:paddingRight="10dp" android:layout_marginLeft="15dp"/> <TextView android:id="@+id/id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@+id/icon" android:paddingBottom="10dp" android:layout_marginTop="25dp" android:textColor="#CC0033" android:textSize="16dp" android:layout_marginLeft="20dp" android:text="yes"/> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/id" android:layout_toRightOf="@+id/icon" android:paddingLeft="10dp" android:layout_marginLeft="20dp" android:textColor="#3399FF" android:textSize="14dp" android:text="no"/> <TextView android:id="@+id/email" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/name" android:layout_toRightOf="@+id/icon" android:layout_marginLeft="20dp" android:paddingLeft="10dp" android:textColor="#3399FF" android:textSize="14dp" android:text="no no no"/> <TextView android:id="@+id/mobile" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/email" android:layout_toRightOf="@+id/icon" android:layout_marginLeft="20dp" android:paddingLeft="10dp" android:textColor="#3399FF" android:textSize="14dp" android:text="no no no"/> <TextView android:id="@+id/address" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/mobile" android:layout_toRightOf="@+id/icon" android:layout_marginLeft="20dp" android:paddingLeft="10dp" android:textColor="#3399FF" android:textSize="14dp" android:text="no no no"/> <TextView android:id="@+id/gender" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/address" android:layout_marginLeft="20dp" android:layout_toRightOf="@+id/icon" android:paddingLeft="10dp" android:textColor="#3399FF" android:textSize="14dp" android:text="no no no"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/gender" android:layout_marginRight="10dp" android:text="Details" android:layout_alignParentRight="true" android:background="@drawable/card" android:textColor="@color/colorPrimary" android:textAllCaps="false" android:id="@+id/det" android:focusable="false" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/gender" android:layout_marginRight="120dp" android:text="Trans" android:layout_alignParentRight="true" android:textColor="@color/colorPrimary" android:background="@drawable/card" android:textAllCaps="false" android:id="@+id/trans" android:focusable="false" /> </RelativeLayout>

活動的屏幕截圖出現錯誤 onclick 的活動圖像

日志:

 java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.loginandregistration/info.androidhive.loginandregistration.activity.CarsInfo}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3623) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3775) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2261) at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:237) at android.app.ActivityThread.main(ActivityThread.java:8107) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at info.androidhive.loginandregistration.activity.CarsInfo.onCreate(CarsInfo.java:46) at android.app.Activity.performCreate(Activity.java:7957) at android.app.Activity.performCreate(Activity.java:7946) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3598) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3775) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2261) at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:237) at android.app.ActivityThread.main(ActivityThread.java:8107) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)

這一行:

startActivity(intent)

需要上下文,這就是您收到此錯誤的原因:

Unable to start activity ComponentInfo

正確的方法是:

context.startActivity(intent)

您需要一個自定義適配器。 大多數示例/教程展示了如何制作一個完整的適配器,但您可以通過使用當前的適配器代碼覆蓋 getView() 來實現。 所以改變:

    ListAdapter adapter = new SimpleAdapter(JsonParsing.this, contactList,
            R.layout.list_item, new String[]{"id", "name","email","mobile","address","gender"},
            new int[]{R.id.id,R.id.name,R.id.email, R.id.mobile,R.id.address,R.id.gender});

    ListAdapter adapter = new SimpleAdapter(JsonParsing.this, contactList,
            R.layout.list_item, new String[]{"id", "name","email","mobile","address","gender"},
            new int[]{R.id.id,R.id.name,R.id.email, R.id.mobile,R.id.address,R.id.gender}){

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = super.getView(position, convertView, parent);

            // Codes that do custom things.
            Button trans = view.findViewById(R.id.trans);
            trans.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(JsonParsing.this, MainActivity.class);
                    HashMap<String, String> contact = (HashMap<String, String>) getItem(position);
                    intent.putExtra("id", contact.get("id"));
                    intent.putExtra("name", contact.get("name"));
                    intent.putExtra("email", contact.get("email"));
                    intent.putExtra("mobile", contact.get("mobile"));
                    intent.putExtra("address", contact.get("address"));
                    intent.putExtra("gender", contact.get("gender"));
                    startActivity(intent);
                }
            });

            return view;
        }
    };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM