选择列表行时打开活动

时间:2014-04-08 17:37:24

标签: android

在Android应用程序中,我使用JSON来获取MySQL对象。在活动中,我在列表中显示对象。选择其中一个对象后,应该打开一个新活动,但是有一个我无法找到的错误。

这是应该打开第二个活动的第一个活动的代码的一部分:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_categorias);

    contactList = new ArrayList<HashMap<String, String>>();

    ListView lv = getListView();

    // Listview on item click listener
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name))
                    .getText().toString();
            String cost = ((TextView) view.findViewById(R.id.email))
                    .getText().toString();


            //Starting single contact activity
            Intent in = new Intent(getApplicationContext(),
                    ofertas_list.class);
            in.putExtra(TAG_NAME, name);
            in.putExtra(TAG_ID, cost);

            startActivity(in);

        }
    });

    // Calling async task to get json
    new GetContacts().execute();
}

这里是第二个活动中未打开的部分代码,会引发错误。

 // JSON node keys
    private static final String TAG_NAME = "nombreCategoria";
    private static final String TAG_ID = "idCategoria";

 // getting intent data
    Intent in = getIntent();

    // Get JSON values from previous intent
    String name = in.getStringExtra(TAG_NAME);
    String email = in.getStringExtra(TAG_ID);

这是错误日志

04-08 13:24:04.053: E/AndroidRuntime(1321): FATAL EXCEPTION: main
04-08 13:24:04.053: E/AndroidRuntime(1321): Process: com.example.vivegrancanaria2014_001, PID: 1321
04-08 13:24:04.053: E/AndroidRuntime(1321): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.vivegrancanaria2014_001/com.example.vivegrancanaria2014_001.ofertas_list}: java.lang.NullPointerException
04-08 13:24:04.053: E/AndroidRuntime(1321):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
04-08 13:24:04.053: E/AndroidRuntime(1321):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-08 13:24:04.053: E/AndroidRuntime(1321):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-08 13:24:04.053: E/AndroidRuntime(1321):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-08 13:24:04.053: E/AndroidRuntime(1321):     at android.os.Handler.dispatchMessage(Handler.java:102)
04-08 13:24:04.053: E/AndroidRuntime(1321):     at android.os.Looper.loop(Looper.java:136)
04-08 13:24:04.053: E/AndroidRuntime(1321):     at android.app.ActivityThread.main(ActivityThread.java:5017)
04-08 13:24:04.053: E/AndroidRuntime(1321):     at java.lang.reflect.Method.invokeNative(Native Method)
04-08 13:24:04.053: E/AndroidRuntime(1321):     at java.lang.reflect.Method.invoke(Method.java:515)
04-08 13:24:04.053: E/AndroidRuntime(1321):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-08 13:24:04.053: E/AndroidRuntime(1321):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-08 13:24:04.053: E/AndroidRuntime(1321):     at dalvik.system.NativeStart.main(Native Method)
04-08 13:24:04.053: E/AndroidRuntime(1321): Caused by: java.lang.NullPointerException
04-08 13:24:04.053: E/AndroidRuntime(1321):     at com.example.vivegrancanaria2014_001.ofertas_list.<init>(ofertas_list.java:35)
04-08 13:24:04.053: E/AndroidRuntime(1321):     at java.lang.Class.newInstanceImpl(Native Method)
04-08 13:24:04.053: E/AndroidRuntime(1321):     at java.lang.Class.newInstance(Class.java:1208)
04-08 13:24:04.053: E/AndroidRuntime(1321):     at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
04-08 13:24:04.053: E/AndroidRuntime(1321):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
04-08 13:24:04.053: E/AndroidRuntime(1321):     ... 11 more

我需要你的帮助来解释错误日志,我无法找到崩溃原因。

谢谢

修改

以下是第二项活动的代码:

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class ofertas_list extends ListActivity {

    private ProgressDialog pDialog;

 // JSON node keys
    private static final String TAG_NAME = "nombreCategoria";
    private static final String TAG_ID = "idCategoria";

 // getting intent data
    Intent in = getIntent();

    // Get JSON values from previous intent
    String name = in.getStringExtra(TAG_NAME);
    String email = in.getStringExtra(TAG_ID);

 // JSON node keys

      private static final String TAG_CATEGORIAS = "Categorias";//valor del nodo principal
    // Get JSON values from previous intent




    // URL to get contacts JSON
    private static String url = "http://xxxxxxxxx";//not shown for security reasond

    // JSON Node names

    private static final String TAG_NOMBREEMPRESA = "nombreEmpresa";
    private static final String TAG_IDEMPRESA = "idEmpresa";
    private static final String TAG_DESCRIPCIONEMPRESA = "descripcionEmpresa";
    private static final String TAG_STRIMAGEN = "strImagen";
    private static final String TAG_DIRECCIONEMPRESA = "direccionEmpresa";
    private static final String TAG_TELEFONOEMPRESA = "telefonoEmpresa";
    private static final String TAG_FACEBOOKEMPRESA = "facebookEmpresa";
    private static final String TAG_EMAILEMPRESA = "emailEmpresa";
    private static final String TAG_TEXTOOFERTA = "textoOferta";
    private static final String TAG_HORARIOEMPRESA = "horarioEmpresa";
    private static final String TAG_CATEGORIAEMPRESA = "categoriaEmpresa";
    private static final String TAG_LATITUDEMPRESA = "latitudEmpresa";
    private static final String TAG_LONGITUDEMPRESA = "longitudEmpresa";
    private static final String TAG_VALORACIONEMPRESA = "valoracionEmpresa";



    // contacts JSONArray
    JSONArray contacts = null;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_categorias);

        contactList = new ArrayList<HashMap<String, String>>();

        ListView lv = getListView();

        // Listview on item click listener
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem

                //cambiar por los nuevos campos
                String name = ((TextView) view.findViewById(R.id.name))
                        .getText().toString();
                String cost = ((TextView) view.findViewById(R.id.email))
                        .getText().toString();


                //Starting single contact activity
                //cambiar por los nuevos campos
                Intent in = new Intent(getApplicationContext(),
                        SingleContactActivity.class);
                in.putExtra(TAG_NAME, name);
                in.putExtra(TAG_ID, cost);

                startActivity(in);

            }
        });

        // Calling async task to get json
        new GetContacts().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     * */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(ofertas_list.this);
            pDialog.setMessage("Cargando datos...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    contacts = jsonObj.getJSONArray(TAG_CATEGORIAS);

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);


                        String nombreEmpresa = c.getString(TAG_NOMBREEMPRESA);
                        String descripcionEmpresa = c.getString(TAG_DESCRIPCIONEMPRESA);
                        String strImagen = c.getString(TAG_STRIMAGEN);
                        String direccionEmpresa = c.getString(TAG_DIRECCIONEMPRESA);
                        String telefonoEmpresa = c.getString(TAG_TELEFONOEMPRESA);
                        String facebookEmpresa = c.getString(TAG_FACEBOOKEMPRESA);
                        String emailEmpresa = c.getString(TAG_EMAILEMPRESA);
                        String textoOferta = c.getString(TAG_TEXTOOFERTA);
                        String horarioEmpresa = c.getString(TAG_HORARIOEMPRESA);
                        String categoriaEmpresa = c.getString(TAG_CATEGORIAEMPRESA);
                        String valoracionEmpresa = c.getString(TAG_VALORACIONEMPRESA);
                        String latitudEmpresa = c.getString(TAG_LATITUDEMPRESA);
                        String longitudEmpresa = c.getString(TAG_LONGITUDEMPRESA);
                        String idEmpresa = c.getString(TAG_IDEMPRESA);




                        // Phone node is JSON Object

                        // tmp hashmap for single contact
                        HashMap<String, String> contact = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        contact.put(TAG_IDEMPRESA, idEmpresa);
                        contact.put(TAG_NOMBREEMPRESA, nombreEmpresa);
                        contact.put(TAG_DESCRIPCIONEMPRESA,descripcionEmpresa);
                        contact.put(TAG_STRIMAGEN,strImagen);
                        contact.put(TAG_DIRECCIONEMPRESA,direccionEmpresa);
                        contact.put(TAG_TELEFONOEMPRESA,telefonoEmpresa);
                        contact.put(TAG_FACEBOOKEMPRESA,facebookEmpresa);
                        contact.put(TAG_EMAILEMPRESA,emailEmpresa);
                        contact.put(TAG_TEXTOOFERTA,textoOferta);
                        contact.put(TAG_HORARIOEMPRESA,horarioEmpresa);
                        contact.put(TAG_CATEGORIAEMPRESA,categoriaEmpresa);
                        contact.put(TAG_VALORACIONEMPRESA,valoracionEmpresa);
                        contact.put(TAG_LATITUDEMPRESA,latitudEmpresa);
                        contact.put(TAG_LONGITUDEMPRESA,longitudEmpresa);






                        // adding contact to contact list
                        contactList.add(contact);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    ofertas_list.this, contactList,
                    R.layout.list_item_ofertas, new String[] { TAG_NOMBREEMPRESA, TAG_DIRECCIONEMPRESA}, new int[] { R.id.name,
                            R.id.email });

            setListAdapter(adapter);
        }

    }

}

3 个答案:

答案 0 :(得分:5)

在onCreate之前不要初始化变量,你只需声明变量并在onCreate方法中初始化它们。这将解决你的问题

答案 1 :(得分:1)

  

//Starting single contact activity
            Intent in = new Intent(getApplicationContext(),
                    ofertas_list.class);

而不是getApplicationContext()使用CurrentActivity.this或只是&#34;这&#34;。

另外,请你完整地发布ofertas_list.class。因为看起来可能是问题所在。

答案 2 :(得分:-2)

java.lang.NullPointerException意味着你的一个变量是null,只需将点放在行列中并尝试调试......你会找到空指针所在的位置&amp;解决你的问题。 试试这个&#39;而不是getApplicationContext()。