Question

I have a android application that makes a json call to a website. But as soon as I add an event for a button my program stop working

Here is my code for my button:

Button btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
        new LoadAllProducts().execute();
   }
});

Here is my code for the new LoadAllProducts().execute():

class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Login.this);
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", "andre"));
            params.add(new BasicNameValuePair("password", "aaa"));
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest("http://mobirep.co.za/server_scripts/check_login/check_login.php", "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt("success");

                TAG_NAME = json.getString("success");
                if (success == 1) {

                }
                else 
                {

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    TextView tx = (TextView)findViewById(R.id.Tests);
                    tx.setText(TAG_NAME + TAG_ID);
                }
            });

        }

    }

Here is my LogCat:

05-14 07:14:23.718: D/AndroidRuntime(914): Shutting down VM
05-14 07:14:23.718: W/dalvikvm(914): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
05-14 07:14:23.738: E/AndroidRuntime(914): FATAL EXCEPTION: main
05-14 07:14:23.738: E/AndroidRuntime(914): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobirep.app/com.mobirep.app.Login}: java.lang.NullPointerException
05-14 07:14:23.738: E/AndroidRuntime(914):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
05-14 07:14:23.738: E/AndroidRuntime(914):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-14 07:14:23.738: E/AndroidRuntime(914):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-14 07:14:23.738: E/AndroidRuntime(914):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-14 07:14:23.738: E/AndroidRuntime(914):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-14 07:14:23.738: E/AndroidRuntime(914):  at android.os.Looper.loop(Looper.java:137)
05-14 07:14:23.738: E/AndroidRuntime(914):  at android.app.ActivityThread.main(ActivityThread.java:5041)
05-14 07:14:23.738: E/AndroidRuntime(914):  at java.lang.reflect.Method.invokeNative(Native Method)
05-14 07:14:23.738: E/AndroidRuntime(914):  at java.lang.reflect.Method.invoke(Method.java:511)
05-14 07:14:23.738: E/AndroidRuntime(914):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-14 07:14:23.738: E/AndroidRuntime(914):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-14 07:14:23.738: E/AndroidRuntime(914):  at dalvik.system.NativeStart.main(Native Method)
05-14 07:14:23.738: E/AndroidRuntime(914): Caused by: java.lang.NullPointerException
05-14 07:14:23.738: E/AndroidRuntime(914):  at com.mobirep.app.Login.onCreate(Login.java:52)
05-14 07:14:23.738: E/AndroidRuntime(914):  at android.app.Activity.performCreate(Activity.java:5104)
05-14 07:14:23.738: E/AndroidRuntime(914):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
05-14 07:14:23.738: E/AndroidRuntime(914):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
05-14 07:14:23.738: E/AndroidRuntime(914):  ... 11 more
05-14 07:15:08.587: E/Trace(963): error opening trace file: No such file or directory (2)
05-14 07:15:09.977: D/AndroidRuntime(963): Shutting down VM
05-14 07:15:09.977: W/dalvikvm(963): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
05-14 07:15:09.997: E/AndroidRuntime(963): FATAL EXCEPTION: main
05-14 07:15:09.997: E/AndroidRuntime(963): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobirep.app/com.mobirep.app.Login}: java.lang.NullPointerException
05-14 07:15:09.997: E/AndroidRuntime(963):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
05-14 07:15:09.997: E/AndroidRuntime(963):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-14 07:15:09.997: E/AndroidRuntime(963):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-14 07:15:09.997: E/AndroidRuntime(963):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-14 07:15:09.997: E/AndroidRuntime(963):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-14 07:15:09.997: E/AndroidRuntime(963):  at android.os.Looper.loop(Looper.java:137)
05-14 07:15:09.997: E/AndroidRuntime(963):  at android.app.ActivityThread.main(ActivityThread.java:5041)
05-14 07:15:09.997: E/AndroidRuntime(963):  at java.lang.reflect.Method.invokeNative(Native Method)
05-14 07:15:09.997: E/AndroidRuntime(963):  at java.lang.reflect.Method.invoke(Method.java:511)
05-14 07:15:09.997: E/AndroidRuntime(963):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-14 07:15:09.997: E/AndroidRuntime(963):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-14 07:15:09.997: E/AndroidRuntime(963):  at dalvik.system.NativeStart.main(Native Method)
05-14 07:15:09.997: E/AndroidRuntime(963): Caused by: java.lang.NullPointerException
05-14 07:15:09.997: E/AndroidRuntime(963):  at com.mobirep.app.Login.onCreate(Login.java:52)
05-14 07:15:09.997: E/AndroidRuntime(963):  at android.app.Activity.performCreate(Activity.java:5104)
05-14 07:15:09.997: E/AndroidRuntime(963):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
05-14 07:15:09.997: E/AndroidRuntime(963):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
05-14 07:15:09.997: E/AndroidRuntime(963):  ... 11 more
05-14 07:15:17.377: I/Process(963): Sending signal. PID: 963 SIG: 9
05-14 07:15:53.767: D/dalvikvm(1025): GC_CONCURRENT freed 109K, 8% free 2686K/2916K, paused 9ms+6ms, total 176ms
05-14 07:15:53.767: D/gralloc_goldfish(1025): Emulator without GPU emulation detected.
05-14 07:37:34.787: D/AndroidRuntime(1156): Shutting down VM
05-14 07:37:34.798: W/dalvikvm(1156): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
05-14 07:37:34.817: E/AndroidRuntime(1156): FATAL EXCEPTION: main
05-14 07:37:34.817: E/AndroidRuntime(1156): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobirep.app/com.mobirep.app.Login}: java.lang.NullPointerException
05-14 07:37:34.817: E/AndroidRuntime(1156):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
05-14 07:37:34.817: E/AndroidRuntime(1156):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-14 07:37:34.817: E/AndroidRuntime(1156):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-14 07:37:34.817: E/AndroidRuntime(1156):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-14 07:37:34.817: E/AndroidRuntime(1156):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-14 07:37:34.817: E/AndroidRuntime(1156):     at android.os.Looper.loop(Looper.java:137)
05-14 07:37:34.817: E/AndroidRuntime(1156):     at android.app.ActivityThread.main(ActivityThread.java:5041)
05-14 07:37:34.817: E/AndroidRuntime(1156):     at java.lang.reflect.Method.invokeNative(Native Method)
05-14 07:37:34.817: E/AndroidRuntime(1156):     at java.lang.reflect.Method.invoke(Method.java:511)
05-14 07:37:34.817: E/AndroidRuntime(1156):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-14 07:37:34.817: E/AndroidRuntime(1156):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-14 07:37:34.817: E/AndroidRuntime(1156):     at dalvik.system.NativeStart.main(Native Method)
05-14 07:37:34.817: E/AndroidRuntime(1156): Caused by: java.lang.NullPointerException
05-14 07:37:34.817: E/AndroidRuntime(1156):     at com.mobirep.app.Login.onCreate(Login.java:52)
05-14 07:37:34.817: E/AndroidRuntime(1156):     at android.app.Activity.performCreate(Activity.java:5104)
05-14 07:37:34.817: E/AndroidRuntime(1156):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
05-14 07:37:34.817: E/AndroidRuntime(1156):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
05-14 07:37:34.817: E/AndroidRuntime(1156):     ... 11 more
05-14 07:42:35.057: I/Process(1156): Sending signal. PID: 1156 SIG: 9

Here is my login.java:

package com.mobirep.app;

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

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class Login extends ActionBarActivity {

    //
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
    String TAG_SUCCESS = "success";
    String TAG_ID = "id";
    String TAG_NAME = "name";
    //buttons

    //

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //new LoadAllProducts().execute();
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
        Button btnLogin = (Button)findViewById(R.id.btnLogin);
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Check_Login().execute();
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.login, 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);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_login,
                    container, false);
            return rootView;
        }
    }


    class Check_Login extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Login.this);
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", "andre"));
            params.add(new BasicNameValuePair("password", "aaa"));
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest("http://mobirep.co.za/server_scripts/check_login/check_login.php", "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt("success");

                TAG_NAME = json.getString("success");
                if (success == 1) {

                }
                else 
                {

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    TextView tx = (TextView)findViewById(R.id.Tests);
                    tx.setText(TAG_NAME + TAG_ID);
                }
            });

        }

    }
}

It is 2 classes that is in one file login.java Could you please assist me on this error or give me and feedback? If there are any other questions that are related please let me know.

Thank you so much

my new oncreate code:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //new LoadAllProducts().execute();
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
        View rootView = Inflater.inflate(R.layout.fragment_login, container, false);
        Button btnLogin = (Button)rootView.findViewById(R.id.btnLogin);
        btnLogin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //new Check_Login().execute();
                Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_SHORT).show();
                Log.d("Info:", "awe");
            }
        });          
    }
Was it helpful?

Solution

This is because findViewById() searches in the activity_main layout, while the button is located in the fragment's layout fragment_main.

Move that piece of code in the onCreateView() method of the fragment:

//...

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        onButtonClick((Button) view);
    }
});

Notice that now you access it through rootView view:

Button buttonClick = (Button)rootView.findViewById(R.id.button);

otherwise you would get again NullPointerException.

OTHER TIPS

remove the button declaration and the onClick assigned from the MainActivity class and create the following method in the Fragment class:

@Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Button btnLogin = (Button) view.findViewById(R.id.btnLogin);

        btnLogin.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {
                new LoadAllProducts().execute();
        }
   });

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top