0

I'm want to open a new activity by clicking an item in the listView. Unfortunately I'm always getting this error. Tried several tutorials and read several questions, I'm not able to work this out.

MainActivity.java

public class MainActivity extends Activity {

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.action_email:
                openMail();
                return true;
            case R.id.action_refresh:
                refreshFeed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void openMail(){
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("plain/text");
        intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "arjun@techulus.com" });
        intent.putExtra(Intent.EXTRA_SUBJECT, "WFW");
        //intent.putExtra(Intent.EXTRA_TEXT, "mail body");
        startActivity(Intent.createChooser(intent, ""));
    }

    public void refreshFeed() {

        listView = (ListView) findViewById(R.id.list);

        feedItems = new ArrayList<FeedItem>();

        listAdapter = new FeedListAdapter(this, feedItems);
        listView.setAdapter(listAdapter);

        listView.setOnItemClickListener(new ListView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> a, View v, int i, long l) {

               openMail();
            }
        });

            // making fresh volley request and getting json
            JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
                    URL_FEED, null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    VolleyLog.d(TAG, "Response: " + response.toString());
                    if (response != null) {
                        parseJsonFeed(response);
                    }
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                }
            }
            );

            // Adding request to volley request queue
            AppController.getInstance().addToRequestQueue(jsonReq);
    }

    private static final String TAG = MainActivity.class.getSimpleName();
    private ListView listView;
    private FeedListAdapter listAdapter;
    private List<FeedItem> feedItems;
    private String URL_FEED = "http://wirefreeworld.in/api/list.php";

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        ListView lv = getListView();

        // listening to single list item on click
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                // selected item
                String product = "Test";

                // Launching new Activity on selecting single List Item
                Intent i = new Intent(getApplicationContext(), product.class);
                // sending data to new activity
                i.putExtra("product", product);
                startActivity(i);

            }
        });

        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.list);

        feedItems = new ArrayList<FeedItem>();

        listAdapter = new FeedListAdapter(this, feedItems);
        listView.setAdapter(listAdapter);

        // These two lines not needed,
        // just to get the look of facebook (changing background color & hiding the icon)
        getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#333333")));
        getActionBar().setIcon(
                new ColorDrawable(getResources().getColor(android.R.color.transparent)));


            // making fresh volley request and getting json
            JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
                    URL_FEED, null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    VolleyLog.d(TAG, "Response: " + response.toString());
                    if (response != null) {
                        parseJsonFeed(response);
                    }
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                }
            }
            );

            // Adding request to volley request queue
            AppController.getInstance().addToRequestQueue(jsonReq);
    }

    /**
     * Parsing json reponse and passing the data to feed view list adapter
     * */
    private void parseJsonFeed(JSONObject response) {
        try {
            JSONArray feedArray = response.getJSONArray("feed");

            for (int i = 0; i < feedArray.length(); i++) {
                JSONObject feedObj = (JSONObject) feedArray.get(i);

                FeedItem item = new FeedItem();
                item.setId(feedObj.getInt("id"));
                item.setName(feedObj.getString("title"));

                // Image might be null sometimes
                String image = feedObj.isNull("photo1") ? null : feedObj
                        .getString("photo1");
                item.setImge(image);
                //item.setStatus(feedObj.getString("status"));
                //item.setProfilePic("http://wirefreeworld.in/logo/logo.png");
                //item.setTimeStamp(feedObj.getString("timeStamp"));

                // url might be null sometimes
                String feedUrl = feedObj.isNull("url") ? null : feedObj
                        .getString("url");
                item.setUrl(feedUrl);

                feedItems.add(item);
            }

            // notify data changes to list adapater
            listAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


}

product.java

public class product extends ActionBarActivity {

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

        TextView txtProduct = (TextView) findViewById(R.id.product_label);

        Intent i = getIntent();
        // getting attached intent data
        String product = i.getStringExtra("product");
        // displaying selected product name
        txtProduct.setText(product);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.product, 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);
    }
}
Andrew T.
  • 4,701
  • 8
  • 43
  • 62
Arjun Komath
  • 2,802
  • 4
  • 16
  • 24
  • possible duplicate of [how to use getListView() in Activity?](http://stackoverflow.com/questions/6275559/how-to-use-getlistview-in-activity) – Andrew T. Sep 05 '14 at 08:11
  • I read that question and checked the xml file and it has an attribute `android:id="@+id/list"` , what else has to be done to? – Arjun Komath Sep 05 '14 at 08:17
  • The link is actually an alternative if you want to use `Activity` (or `FragmentActivity` or `ActionBarActivity`) instead of `ListActivity`. Sorry for the confusion. – Andrew T. Sep 05 '14 at 08:21
  • @AndrewT. There was another instance for the same list, I removed that and the error is gone. Thank you. There is some issue with the intent function. The application is crashing as soon as I launch it. – Arjun Komath Sep 05 '14 at 08:28
  • Reading your comment below, maybe [this question](http://stackoverflow.com/questions/1026973/android-whats-the-difference-between-the-various-methods-to-get-a-context) may help you, especially [this answer](http://stackoverflow.com/a/13945633/2821954) (though it'd be better to read all other answers too). In that case, I'd use `Intent i = new Intent(this, product.class)`. You may also need to check if "product" activity is already registered on the manifest or not. – Andrew T. Sep 05 '14 at 08:33
  • @AndrewT. `Intent i = new Intent (MainActivity.this, product.class);` The app crashed as soon as I click on the list item. – Arjun Komath Sep 05 '14 at 09:12
  • You should check the exception on the LogCat, then search it on Google or SO. If you really can't find anything, you may then ask a new question regarding that issue, possibly by including the link to this question. – Andrew T. Sep 05 '14 at 09:16

2 Answers2

2

In order to have the method getListView() available your activity class must extend ListActivity class and not the Activity.

ListActivity has a default layout that consists of a single, full-screen list in the center of the screen. However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate(). To do this, your own view MUST contain a ListView object with the id "@android:id/list" (or list if it's in code)

makovkastar
  • 5,000
  • 2
  • 30
  • 50
  • there was a duplicate in the getlistView. But still the intent function is failing `// Launching new Activity on selecting single List Item Intent i = new Intent(getApplicationContext(), product.class); // sending data to new activity i.putExtra("product", product); startActivity(i); }` – Arjun Komath Sep 05 '14 at 08:25
0

For method getListView() , Your activity class must extend ListActivity and your layout MUST contain a ListView object with the id "@android:id/list"

Happy Coding :)

Priyanka
  • 677
  • 5
  • 20