如何从简单列表视图的按钮打开新活动

Posted

技术标签:

【中文标题】如何从简单列表视图的按钮打开新活动【英文标题】:How to open new activity from button of simple list view 【发布时间】:2021-02-14 11:47:24 【问题描述】:

Devs 我遇到了一个严重的问题我有一个简单的列表视图,它有一个图像视图和几个文本视图来显示一些文本和两个按钮。现在的问题是,当我在按钮上设置单击侦听器时发生空指针错误。我用谷歌搜索了这个问题并找到了一个解决方案来制作自定义适配器来解决这个问题,但我不想使用自定义适配器有没有办法在我的代码下面没有自定义适配器类的情况下解决这个问题:

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_
    android:layout_
    android:background="@color/colorPrimaryDark">
    <ImageView
        android:id="@+id/icon"
        android:layout_
        android:layout_
       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_
        android:layout_
        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_
        android:layout_
        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_
        android:layout_
        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_
        android:layout_
        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_
        android:layout_
        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_
        android:layout_
        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_
        android:layout_
        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_
        android:layout_
        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>

活动截图 Image of activity which give errors onclick

Logcat:

 java.lang.RuntimeException: Unable to start activity ComponentInfoinfo.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) 

【问题讨论】:

请在此处添加您的 logcat。 应用开发请查看logcat 【参考方案1】:

您需要一个自定义适配器。大多数示例/教程展示了如何制作一个完整的适配器,但您可以通过使用当前适配器代码覆盖 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;
        
    ;

【讨论】:

谢谢,兄弟的工作就像一个魅力,现在我通过这个按钮发送 JSON 对象?【参考方案2】:

这一行:

startActivity(intent)

需要上下文,这就是您收到此错误的原因:

Unable to start activity ComponentInfo

正确的做法是:

context.startActivity(intent)

【讨论】:

问题是我想在按钮上设置onclick但是有错误 因为您的项目有一个自定义布局,您需要创建一个自定义适配器并在那里放置 onclick 侦听器。 是的,我知道这一点,但我不知道如何制作这个自定义适配器,如果你帮助我这样做,我对 android 开发非常陌生,这将节省我很多时间,我将非常感谢你 这里是自定义适配器的一个很好的例子:***.com/questions/8166497/…

以上是关于如何从简单列表视图的按钮打开新活动的主要内容,如果未能解决你的问题,请参考以下文章

从列表视图中单击歌曲后,新活动正在打开但歌曲未播放

如何保存android活动的状态

如何使用来自另一个活动的自定义适配器更新列表视图?

当我单击列表视图的按钮时,如何进入其他活动?

通过 REST API 检索结果并将其显示在新活动的列表视图中(列表视图出现小问题)

将多个项目添加到列表视图,每个项目从按钮单击的另一个意图接收