Starting a new layout (activity) from a ListView is a simple process

Whenever the ListView is clicked, I want to initiate a new Activity

This is my MainActivity.java

package com.theheran.listviewicon;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
    //Array Declaration Menu and image
    ListView list;
    String[] menu = {
            "@The_Heran",
            "www.theheran.com",
            "Add",
            "Delete",
            "Next",
            "Back",
            "Find",
            "Warning"
    } ;
    Integer[] imageId = {
            R.drawable.ic_launcher,
            R.drawable.signal,
            R.drawable.add,
            R.drawable.trash,
            R.drawable.next,
            R.drawable.back,
            R.drawable.find,
            R.drawable.warning
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        CustomListView adapter = new
        CustomListView(MainActivity.this, menu, imageId);

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

        list.setAdapter(adapter);

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                Toast.makeText(MainActivity.this, "You Clicked at " +menu[+ position], Toast.LENGTH_SHORT).show();

      // THIS IS WHERE THE ISSUE LIES     (Intent)           
                Intent intent = new CustomListView(MainActivity.this,); 
                startActivity(intent);


            }
        });
    }

}

My CustomListView

package com.theheran.listviewicon;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomListView extends  ArrayAdapter<String> {
    //Declaration
    private final Activity context;
    private final String[] web;
    private final Integer[] imageId;

    public CustomListView(Activity context,String[] web, Integer[] imageId) {
        super(context, R.layout.list_single_data, web);
        this.context = context;
        this.web = web;
        this.imageId = imageId;

    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
            LayoutInflater inflater = context.getLayoutInflater();
            //Load Custom Layout for list 
            View rowView= inflater.inflate(R.layout.list_single_data, null, true);
            //Components Declaration
            TextView txtTitle = (TextView) rowView.findViewById(R.id.txtList);
            ImageView imageView = (ImageView) rowView.findViewById(R.id.imgIcon);

            //Set Parameter Value
            txtTitle.setText(web[position]);
            imageView.setImageResource(imageId[position]);

            return rowView;
        }
}

Answer №1

// ISSUE HERE (Objective)
Intent intent = new CustomListView(MainActivity.this,); startActivity(intent);

It seems like you are attempting to utilize an incorrect format. Try using the following:

Intent intent = new Intent(MainActivity.this, NextActivity.class);
MainActivity.this.startActivity(intent );

Answer №2

Here is a suggested approach:

list.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "You tapped on item " + position, Toast.LENGTH_SHORT).show();
                Intent moveToNext = new Intent(getApplicationContext(), YourNextActivity.class);
                startActivity(moveToNext);

            }
        });

Answer №3

Here is my approach to the problem. To start a new activity, you can use the method

startActivityForResult(intent, 2);
. This allows you to pass an intent and a number (which you can later check when returning to the original page).

private void setButtonClickList() {
        ListView list = (ListView) findViewById(R.id.listView);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {                             

                Intent intent = new Intent(CurrentClass.this, NextClass.class);
                intent.putExtra("Position", position);
                startActivityForResult(intent, 0);

            }
        });
    }

This should be implemented in the same class where you initiated the previous activity from the list. It's important because you are anticipating a result when using startActivityForResult().

protected void onActivityResult(int requestCode, int resultCode, Intent data)                   
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {                                                                    
            if (resultCode == Activity.RESULT_OK) {                                                 
                //Implement actions based on the requestCode
                //and verify if it was successful
            }
            if (resultCode == Activity.RESULT_CANCELED) {     
                //Define behavior for cancellation
            }
        }
}

In the activity that you launched, ensure you include the following code to return a value. Use setResult() for this purpose.

Button btn = (Button) findViewById(R.id.btn);

btnCANCEL.setOnClickListener(new View.OnClickListener() {
@TargetApi(Build.VERSION_CODES.CUPCAKE)
@Override
public void onClick(View v) {
        Intent intent = new Intent();
        setResult(Activity.RESULT_OK, intent);
        //intent.putExtra("something", something); in case you need to send additional data back
        finish();
        }
});

I hope this explanation clears things up!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered: java.lang.NoClassDefFoundError: Unable to resolve class: com.google.firebase.FirebaseApp$IdTokenListener;

I'm currently exploring the use of Firebase for a basic CRUD Android application. However, during the instantiation of a Firebase database reference, I encountered an exception at runtime: java.lang.RuntimeException: Uncaught exception in Firebase Da ...

Issue with displaying Jquery AJAX response in specific div

Having trouble with my JQUERY function. I've got an onclick event triggering a dialog box to open. But upon opening, the dialog box calls two separate jQuery functions. Both functions are supposed to fetch member information based on ID, but only on ...

Convert the encoding of the FileReader's output to UTF-8

I am currently working on a small function that is meant to fetch the contents of an uploaded text file. upload() { let reader = new FileReader(); reader.onload = () => { console.log(reader.result); } reader.readAsText(this.file ...

How can I create an input field that comes with a preset value but can be updated by the user with a different name?

I am in need of a solution that will enable a user to update text on a webpage dynamically. I have been unable to find any information on how to achieve this. Is there anyone aware of a method to implement this feature? Perhaps a library or utilizing Vue ...

Ensure that the video continues playing from where the host left off instead of restarting from the beginning upon reloading

Is there a way to seamlessly stream a video from the host server on my website, so that it picks up exactly where it left off rather than starting from the beginning every time someone accesses the site? I want the video to remain synchronized with the o ...

Sending data from multiple HTML table rows at once to a Django model

After a user selects items from a list, they can submit the selected items to be saved in a table. The table is dynamically rendered using JavaScript and the data comes from a Map with keys as primary keys and values as descriptions and prices. function d ...

Mongo automatically generates an index with a null key/value pair

After successfully creating a new user using mongoose at a certain route, I noticed that the validation appears in the console and the user is stored in the mongo database. However, when attempting to create a second user with a different username, an erro ...

Time bending

If I have a timestamp saved in variable t using t = System.currentTimeMillis() from some time in the past, how can I retrieve the milliseconds for 12 pm of that same day and the following day after 12 pm? ...

"Utilizing AJAX for real-time search to target the final

Recently, I've been playing around with the AJAX Live Search feature that can be found on this site: http://www.w3schools.com/php/php_ajax_livesearch.asp The way it transfers the input value via AJAX to a php file for comparison is quite interesting ...

Month and year selection feature in ExtJS 4 catalog

I recently came across an interesting Fiddle that featured a Month and Year picker for apps. After finding this Fiddle here, I noticed that it was built using Extjs 5.0, and it worked perfectly. However, when attempting to switch it to version 4.2.1, the l ...

Steps for creating a functional counter in AngularJS

I am attempting to create a counter in AngularJS that will be used for some other purpose once it is working with a variable. However, I am facing an issue where the variable is not updating as expected. Since this will eventually become a more complex com ...

Searching for elements by tag name in JavaScript

Recently, I attempted to create JavaScript code that would highlight an element when a user hovers their cursor over it. My approach involves adding an event listener to every child within the first "nav" tag in the current document: let navigation = docum ...

Manipulate the JQuery code to alter the window's location

I am currently implementing ajax for loading my website content and am looking for a way to update the window location upon successful ajax completion. Is it feasible to update the window location to "/newpage" in order to allow users to navigate back and ...

Programmatically align a dialog below a custom view in an Android application

Within my Android Kotlin app, I have implemented a custom spinner using a dialogFragment. When displaying this spinner on click, I want it to always be positioned beneath a specific view within my CustomView. The code snippet for opening the spinner dialo ...

The dimensions of GridStack items specified in pixels for both height and width

I am facing a challenge with my GridStack items, which each contain elements like graphs that need to be re-rendered when the size of the gridstack item (cell) changes. I am attempting to use the change event on GridStack to detect the modified items and t ...

Tips for preserving scroll position within a division following the redisplay of a division in Vue.js

Within my Laravel and Vue project, I have set up a feature to display posts in a scrollable area. This area is only visible when the 'showFeed' variable is true. <div v-show="showFeed" class="scroll-container" v-scroll=&quo ...

Issue "Every child must be positioned exactly once" encountered while creating ClipPath in Flutter

Recently starting with Flutter, I wanted to create a custom shape for my top bar using Clip Path. I followed some tutorials correctly but encountered the Each child must be laid out exactly once error. Below is the code snippet: class MainPage extends Sta ...

Can you clarify the explanation of Proxy in the Vue 3 console?

When shuffling an array, I keep encountering a strange message in the console. Below is a snippet of my JSON file: [ { "id": 1, "name": "Sushi", "image": "https://images.pexels.com/photos/1640777/ ...

Navigating Through a Java Web Application

When navigating a web application, is it possible to trace the sequence of method calls triggered by clicking a specific button on a webpage? While a Stack Trace can provide insight in the case of an exception, is there a method within Eclipse that can h ...

Ant Integration for JaCoCo Code Coverage in Android

I have been focused on a project that I am eager to implement JaCoCo with. I need assistance with an ongoing issue I have encountered. The project utilizes Ant for automated building and testing, including an Android component. I've been attempting to ...