0

Devs I am stuck in a serious problem I have a simple listview that has one image view and several text views to display some text and two-button. now problem is that when I set click listener on buttons null pointer error occurred. I google this problem and found a solution to make a custom adapter to resolve this problem but I don't want to use a custom adapter is there any way to solve this problem without a custom adapter class below my code :

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 File :

<?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>

Screen Shot Of Activity Image of activity which give errors onclick

Logcat :

 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) 
HasJav
  • 3
  • 2

2 Answers2

0

this line:

startActivity(intent)

needs context, that why you get this error:

Unable to start activity ComponentInfo

the correct way is :

context.startActivity(intent)
Bita Mirshafiee
  • 600
  • 8
  • 14
  • Problem is i want to set onclick on buttons but there is error – HasJav Nov 02 '20 at 05:53
  • Because you have a custom layout for your items, you need to create a custom adapter and there put onclick listener. – Bita Mirshafiee Nov 02 '20 at 05:57
  • Yes i know this but i dont know how to make this custom adapter i am very new to android development if u help me doing this it will be save alot of my time and i will be really thankful to u – HasJav Nov 02 '20 at 06:00
  • here is a good example of custom adapter : https://stackoverflow.com/questions/8166497/custom-adapter-for-list-view – Bita Mirshafiee Nov 02 '20 at 06:16
0

You need a custom adapter. Most samples/tutorials show how to make a complete adapter but you can do it by just override getView() with you current adapter code. So change:

    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});

to

    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;
        }
    };
i_A_mok
  • 2,744
  • 2
  • 11
  • 15