单击ImageView启动ListActivity

时间:2014-07-04 08:11:59

标签: android imageview listactivity

我是android编程的新手。在下面的代码中,我尝试从主activity开始Listview ImageView点击Activity。当我跑它崩溃。请帮我解决这个问题。

执行v.getContext().startActivity(searchResults);时,错误就在行上。

    package com.example.libraryhelpdesk;

    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v7.app.ActionBarActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.RadioButton;
    import android.widget.Toast;

    public class MainActivity extends ActionBarActivity {

        // Creating the widget objects in the layout
        ImageView ivSearch;
        RadioButton rbBooks, rbAuthor, rbPub, rbKey;
        EditText eSearchBar;

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

            // Asiging ID to the widgets
            ivSearch = (ImageView) findViewById(R.id.searchbtn);
            rbBooks = (RadioButton) findViewById(R.id.rbBook);
            rbAuthor = (RadioButton) findViewById(R.id.rbAuthor);
            rbPub = (RadioButton) findViewById(R.id.rbPub);
            rbKey = (RadioButton) findViewById(R.id.rbKeywords);
            eSearchBar = (EditText) findViewById(R.id.seachbar);

            // OnClickListner for ImageView
            ivSearch.setOnClickListener(new View.OnClickListener() {
                String flag = "";

                @Override
                public void onClick(View v) {
                // Set Chosen option of search by the user
                    if (rbBooks.isChecked()) {
                        // Launch B_Search Class
                        flag = "B";
                    } else if (rbAuthor.isChecked()) {
                        // Launch ASearch Class
                        flag = "A";
                    } else if (rbPub.isChecked()) {
                        // Launch PSearch Class
                        flag = "P";
                    } else if (rbKey.isChecked()) {
                        // Launch KSearch Class
                        flag = "K";
                    } else {
                        Toast.makeText(getApplicationContext(),
                                "Please select any one option to search!!",
                                Toast.LENGTH_SHORT).show();
                    }

                    Log.d("CheckLib",flag);
                    if (eSearchBar.getText().toString().trim().length() > 0) {
                        // start activity to view the search results
                        Intent searchResults = new Intent(MainActivity.this, B_Search.class);
                        searchResults.putExtra("sValue", eSearchBar.getText()
                                .toString().trim());
                        searchResults.putExtra("sOption", flag);
                        v.getContext().startActivity(searchResults);
                    } else {
                        Toast.makeText(getApplicationContext(),
                                "Enter the search elements!!", Toast.LENGTH_SHORT)
                                .show();
                    }
                }
            });
        }
    }

我的清单文件......

  <activity
        android:name="com.example.libraryhelpdesk.MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name="B_Search" android:label="@string/res_disp">
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT"/>
            <action android:name="com.libhlpdsk.resultview"/>
        </intent-filter>
    </activity>

logcat错误

07-04 09:29:56.855: D/AndroidRuntime(678): Shutting down VM
07-04 09:29:56.855: W/dalvikvm(678): threadid=1: thread exiting with uncaught exception (group=0xb1a0ad58)  
07-04 09:29:56.875: E/AndroidRuntime(678): FATAL EXCEPTION: main
07-04 09:29:56.875: E/AndroidRuntime(678): Process: com.example.libraryhelpdesk, PID: 678
07-04 09:29:56.875: E/AndroidRuntime(678): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.libraryhelpdesk/com.example.libraryhelpdesk.B_Search}: java.lang.NullPointerException
07-04 09:29:56.875: E/AndroidRuntime(678):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2134)
07-04 09:29:56.875: E/AndroidRuntime(678):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2270)
07-04 09:29:56.875: E/AndroidRuntime(678):  at android.app.ActivityThread.access$800(ActivityThread.java:138)
07-04 09:29:56.875: E/AndroidRuntime(678):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1209)
07-04 09:29:56.875: E/AndroidRuntime(678):  at android.os.Handler.dispatchMessage(Handler.java:102)
07-04 09:29:56.875: E/AndroidRuntime(678):  at android.os.Looper.loop(Looper.java:136)
07-04 09:29:56.875: E/AndroidRuntime(678):  at android.app.ActivityThread.main(ActivityThread.java:5042)
07-04 09:29:56.875: E/AndroidRuntime(678):  at java.lang.reflect.Method.invokeNative(Native Method)
07-04 09:29:56.875: E/AndroidRuntime(678):  at java.lang.reflect.Method.invoke(Method.java:515)
07-04 09:29:56.875: E/AndroidRuntime(678):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:776)
07-04 09:29:56.875: E/AndroidRuntime(678):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
07-04 09:29:56.875: E/AndroidRuntime(678):  at dalvik.system.NativeStart.main(Native Method)
07-04 09:29:56.875: E/AndroidRuntime(678): Caused by: java.lang.NullPointerException
07-04 09:29:56.875: E/AndroidRuntime(678):  at com.example.libraryhelpdesk.B_Search.<init>(B_Search.java:28)
07-04 09:29:56.875: E/AndroidRuntime(678):  at java.lang.Class.newInstanceImpl(Native Method)
07-04 09:29:56.875: E/AndroidRuntime(678):  at java.lang.Class.newInstance(Class.java:1214)
07-04 09:29:56.875: E/AndroidRuntime(678):  at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
07-04 09:29:56.875: E/AndroidRuntime(678):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2125)
07-04 09:29:56.875: E/AndroidRuntime(678):  ... 11 more

B_Search.java的代码

package com.example.libraryhelpdesk;

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

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
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.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class B_Search extends ListActivity {
    // Progress Bar while retrieving data
    private ProgressDialog pDialog;

    // Retrieving values from the previous activity
    Bundle extras = getIntent().getExtras();
    private static String sOption = null;
    private static String sBy = null;

    // URL to retrieve search from
    private static String URL = null;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
    ArrayList<HashMap<String, String>> booksList;

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_BOOKS = "catalogues";
    private static final String TAG_BNAME = "b_name";
    private static final String TAG_BAUTHOR = "b_author";
    private static final String TAG_BID = "b_id";

    // JSON Array
    JSONArray books = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        Log.d("CheckLib","Reached activity B");
        setContentView(R.layout.result_view_item);

        // Initiate the static variables
        sOption = extras.getString("sOption");
        sBy = extras.getString("sValue");
        URL = getURLVal(sOption);

        // Hashmap for ListView
        booksList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadResults().execute();

        // Get listview
//      ListView lv = getListView();
    }

    private static String getURLVal(String sval) {
        // TODO Auto-generated method stub
        String URL = "";
        switch (sval) {
        case "B":
            URL = "http://10.0.2.2:1234/webservices/b_search.php";
        case "A":
            URL = "http://10.0.2.2:1234/webservices/a_search.php";
        case "P":
            URL = "http://10.0.2.2:1234/webservices/p_search.php";
        case "K":
            URL = "http://10.0.2.2:1234/webservices/k_search.php";
        default:
            Log.i("Error", "Option by not found");
        }
        return URL;
    }

    // Background Async Task to Load all product by making HTTP Request
    class LoadResults extends AsyncTask<String, String, String> {

        // Progress Dialog
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            pDialog = new ProgressDialog(B_Search.this);
            pDialog.setMessage("Loading results. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        // Setting URL to be chosen

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("searchvalue", sBy));

            Log.d("request!", "starting");

            // Make HTTP Request
            JSONObject json = jParser.makeHttpRequest(URL, "POST", params);

            Log.d("Login attempt", json.toString());

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

                if (success == 1) {
                    // Books found
                    // Getting Array of books
                    books = json.getJSONArray(TAG_BOOKS);
                    // looping through All books in array
                    for (int i = 0; i < books.length(); i++) {
                        JSONObject temp = books.getJSONObject(i);

                        // Storing each JSON item in variable
                        String id = temp.getString(TAG_BID);
                        String name = temp.getString(TAG_BNAME);
                        String author = temp.getString(TAG_BAUTHOR);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_BID, id);
                        map.put(TAG_BNAME, name);
                        map.put(TAG_BAUTHOR, author);

                        // adding HashList to ArrayList
                        booksList.add(map);
                    }
                } else {
                    // no books found
                    // Launch Main Activity
                    Toast.makeText(getApplicationContext(),
                            "No Books Found. Try Again!!", Toast.LENGTH_LONG)
                            .show();
                    Intent mainact = new Intent(getApplicationContext(),
                            MainActivity.class);
                    // Closing all previous activities
                    startActivity(mainact);
                }
            } 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 the results
            pDialog.dismiss();

            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    // Updating parsed JSON data into ListView
                    ListAdapter adapter = new SimpleAdapter(B_Search.this,
                            booksList, R.layout.result_view_item, new String[] {
                                    TAG_BID, TAG_BNAME, TAG_BAUTHOR },
                            new int[] { R.id.b_id, R.id.b_name, R.id.b_author });
                    // updating listview
                    setListAdapter(adapter);
                }
            });
        }
    }
}

3 个答案:

答案 0 :(得分:1)

Bundle extras = getIntent().getExtras();

您过早地调用getIntent()并返回null。将此代码移至onCreate()

在尝试检索额外值之前,还需要检查getExtras()返回非null值。

答案 1 :(得分:0)

您正在使用ListActivity,相应的xml必须具有ListView且ID为android:id="@android:id/list"的xml文件应该如下所示

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
         >        
        <ListView
            android:id="@android:id/list"
            android:layout_height="wrap_content"
            android:layout_width="match_parent">
        </ListView>

 </RelativeLayout> 

答案 2 :(得分:-1)

MainActivity.this更改为v.getContext()

我认为错误发生在android:name="B_Search",我认为您需要在名称属性之前加上一段时间:android:name=".B_Search"