如何在另一个意图中拆分传递的ListView项?

时间:2016-12-28 17:10:52

标签: java android listview android-intent

我是android和java的新手,我在这个android项目上工作,我有一个ListView电影(Name-String,Genre-String,Year-Int)。我想在将项目传递给另一个activity之后拆分该项目。

我的电影模型:

public class Movie
{
    // property to help us handle the data
    private int id;
    private String name;
    private String genre;
    private int year;


    //Getters and Setters of the properties
    public long getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }


    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }


    public String getGenre()
    {
        return genre;
    }

    public void setGenre(String genre)
    {
        this.genre = genre;
    }


    public int getYear()
    {
        return year;
    }

    public void setYear(int year)
    {
        this.year = year;
    }


    public String toString()
    {
        return name + ", " + genre + ", " + year;
    }



//----------Start--------- Here we have defined the table contents (basically a blueprint of the table Movie) -------------------------------------

    public static final String TABLE_NAME = "movie";
    public static final String COlUMN_ID = "id";
    public static final String COlUMN_NAME = "make";
    public static final String COlUMN_GENRE = "model";
    public static final String COlUMN_YEAR = "year";

//----------------------END----------------------------------------------------------------------------------------------------------------//

}

我的创建电影活动:

 public class CreateMovieActivity extends AppCompatActivity
{
    MoviesRepository moviesRepository;

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

        moviesRepository = new MoviesRepository(this);
        moviesRepository.open();
    }

    public void onClickSaveMovie(View v)
    {
        Button buttonAdd = (Button) v;

        EditText editTextName = (EditText) findViewById(R.id.editTextName);
        EditText editTextGenre = (EditText) findViewById(R.id.editTextGenre);
        EditText editTextYear = (EditText) findViewById(R.id.editTextYear);

        Movie movie = new Movie();
        movie.setName(editTextName.getText().toString());
        movie.setGenre(editTextGenre.getText().toString());
        movie.setYear(Integer.parseInt(editTextYear.getText().toString()));


        moviesRepository.Create(movie);


        Button buttonCreate = (Button) v;
        startActivity(new Intent(getBaseContext(),MainActivity.class));
    }

}

我的电影资料库:

public class MoviesRepository
{
    private SQLiteDatabase db;
    private MyDBHelper myDBHelper;


    private String [] MovieAllColumns ={Movie.COlUMN_ID,
            Movie.COlUMN_NAME,
            Movie.COlUMN_GENRE,
            Movie.COlUMN_YEAR};



    public MoviesRepository(Context context)
    {
        myDBHelper = new MyDBHelper(context);
    }


    public void open() throws SQLException
    {
        //Open connection to write data
        db = myDBHelper.getWritableDatabase();
    }


    public void close()
    {
        //Close connection to database
        db.close();
    }

    private Movie cursorToMovie (Cursor cursor)
    {
        Movie movie = new Movie();
        movie.setId(cursor.getInt(0));
        movie.setName(cursor.getString(1));
        movie.setGenre(cursor.getString(2));
        movie.setYear(cursor.getInt(3));

        return movie;
    }

    public List<Movie> getAllMovies()
    {
        open();

        List<Movie> movieList = new ArrayList<>();
        Cursor cursor = db.query(Movie.TABLE_NAME, MovieAllColumns, null, null, null, null, null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast())
        {
            Movie movie = cursorToMovie(cursor);
            movieList.add(movie);
            cursor.moveToNext();
        }

        cursor.close();
        close();
        return movieList;

    }



    public void Create(Movie movie)
    {
        open();

        //helps you insert values to the table
        ContentValues values = new ContentValues();

        //Put method - first column; what column do you want to be storing this ind. Second; what is the value you want to put ind
        values.put(Movie.COlUMN_NAME, movie.getName());
        values.put(Movie.COlUMN_GENRE, movie.getGenre());
        values.put(Movie.COlUMN_YEAR, movie.getYear());

        db.insert(Movie.TABLE_NAME, null, values);
        close();
    }


    public void Delete(Movie movie)
    {
        open();
        //Deletes Movie by id
        db.delete(Movie.TABLE_NAME, Movie.COlUMN_ID + " = " + movie.getId(), null);
        db.close();
    }

}

当我点击ListView上的某个项目时,它会将该值传递给另一个Activity,我可以将其打印出来(制作吐司)。

这是我将项目传递给其他意图的地方:

 public void Select()
    {
        moviesRepository = new MoviesRepository(this);
        moviesRepository.open();

        final Movie movie;

        final ListView listView = (ListView) findViewById(R.id.ListViewMovie);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                final String details = listView.getAdapter().getItem(position).toString();
                Intent i = new Intent(getApplicationContext(), MovieDetailsActivity.class);
                i.putExtra("key", details);
                startActivity(i);

            }
        });

    } 

但是如何从ListView拆分传递的值,这样才有意义。

这是我想要分成三个值的地方,电影名称,电影类型和年份:

public class MovieDetailsActivity extends AppCompatActivity
{
    TextView movieName;
    TextView movieGenre;
    TextView movieYear;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.movie_details);
        getDetails();
    }
    public void getDetails()
    {
        movieName = (TextView) findViewById(R.id.textViewMovieName);
        movieGenre = (TextView) findViewById(R.id.textViewMovieGenre);
        movieYear = (TextView) findViewById(R.id.textViewMovieYear);

        String data = getIntent().getExtras().getString("key");


        Toast.makeText(this, data, Toast.LENGTH_LONG).show();


    }
}

现在我正在为传递的项目致敬

2 个答案:

答案 0 :(得分:0)

创建一个Apod类,它是单例并具有moviemanager。将电影保存为map到地图中。然后你可以调用<String, Movie>来获取电影对象。

答案 1 :(得分:0)

您正在询问如何在详细信息屏幕中拆分您收到的字符串。

实际上很简单; - )

MovieDetailsActivity#getDetails中,当您从Intent获得详细信息字符串时,您需要执行以下操作:

String data = getIntent().getExtras().getString("key");
String[] splitMovieString = data.split(", ");

然后你可以这样设置TextView

movieName.setText(splitMovieString[0]);
movieGenre.setText(splitMovieString[1]);
movieYear.setText(splitMovieString[2]);

旁注:

通过Intent以字符串形式发送数据的方法是可以的,但它不是Android中在活动之间传递数据的首选方式。

有一种方法可以传递整个Movie对象,但前提是您更改对象以实现Parcelable接口。 (见the official documentation for a full example

实施Parcelable后,您的Movie对象将如下所示:

public class Movie implements Parcelable {
    private int id;
    private String name;
    private String genre;
    private int year;

    protected Movie(Parcel in) {
        id = in.readInt();
        name = in.readString();
        genre = in.readString();
        year = in.readInt();
    }

    public static final Creator<Movie> CREATOR = new Creator<Movie>() {
        @Override
        public Movie createFromParcel(Parcel in) {
            return new Movie(in);
        }

        @Override
        public Movie[] newArray(int size) {
            return new Movie[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeInt(id);
        parcel.writeString(name);
        parcel.writeString(genre);
        parcel.writeInt(year);
    }

   [... Setters, getters and your constants are removed for brevity]
} 

现在,您稍后更改了模型后,可以直接通过Intent系统传递它:

Select内的OnClickListener方法中,您需要稍后更改Intent

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    final Movie selectedMovie = listView.getAdapter().getItem(position);
    Intent detailsIntent = new Intent(getApplicationContext(), MovieDetailsActivity.class);
    detailsIntent.putExtra(Movie.class.getName(), selectedMovie);
    startActivity(detailsIntent);
}

这里发生的事情是我们基本上&#34;压扁&#34; (或序列化)Movie对象到可以通过Intent系统发送的对象中。 现在当您收到Intent中的MovieDetailsActivity#getDetails时,您需要打开(或反序列化)&#34;展平的&#34;再次Movie个对象,这样您就可以像普通Movie对象一样使用它。

所以现在你的MovieDetailsActivity#getDetails应该是这样的:

public void getDetails() {
    movieName = (TextView) findViewById(R.id.textViewMovieName);
    movieGenre = (TextView) findViewById(R.id.textViewMovieGenre);
    movieYear = (TextView) findViewById(R.id.textViewMovieYear);

    Movie movie = getIntent().getParcelableExtra(Movie.class.getName());
    // Now you can set your movie name, genre and year directly from your object.
    movieName.setText(movie.getName());
    movieGenre.setText(movie.getGenre());
    movieYear.setText(String.valueOf(movie.getYear()); // Notice you cannot set an Integer directly as the text of a `TextView`, you need to parse it as a String first.
}

我知道最后一个解决方案会为您的课程带来更多代码,但这确实是实现此目的的最佳方式,当您使模型类实现Parcelable界面时,Android Studio会告诉您#39 ;错过了实施,并实际问你是否需要帮助实施Parcelable,所以你不必自己做很多事情。

最后需要注意的是另一个解决方案,那就是将当前id的{​​{1}}传递到Movie,然后从Intent获取}直接在MoviesRepository中,但是您还必须使用可以从您的回购中获取单个MovieDetailsActivity的新方法扩展您的MoviesRepository

我知道这是一个很长的答案,但这里有许多概念需要处理: - )