java.lang.NullPointerException: Attempt to invoke virtual method android studio [duplicate] - android

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
i have problem with my android studio i want to passing data with parcel but it cant cause i get this message if i click my list view always get force close, how to fix it?
error
package com.example.moviee;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class MovieDetail extends AppCompatActivity {
String txt_name;
String txt_deskripsi;
int foto;
public static final String EXTRA_MOVIE = "text_extra_movie";
TextView tvName, txt_detail;
ImageView imgposter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_detail);
tvName = findViewById(R.id.text_ph);
txt_detail = findViewById(R.id.txt_deksrip);
imgposter = findViewById(R.id.img_poster);
ArrayList<Film> film = new ArrayList<>();
film = this.getIntent().getParcelableArrayListExtra(EXTRA_MOVIE);
txt_name = film.get(0).getNama();
tvName.setText(txt_name);
txt_deskripsi = film.get(0).getDeskripsi();
txt_detail.setText(txt_deskripsi);
foto = film.get(0).getFilm();
imgposter.setImageResource(foto);
}
}
movieDetail.java
package com.example.moviee;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private FilmAdapter adapter;
private String[] dataNama;
private String[] dataDeskrip;
private TypedArray dataPhoto;
private ArrayList<Film> filmed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new FilmAdapter(this);
ListView listView = findViewById(R.id.lv_list);
listView.setAdapter(adapter);
prepare();
addItem();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(MainActivity.this, MovieDetail.class);
ArrayList<Film> movies = new ArrayList<Film>();
Film movie = new Film();
movie.setFilm(dataPhoto.getResourceId(i, -1));
movie.setNama(dataNama[i]);
movie.setDeskripsi(dataDeskrip[i]);
movies.add(movie);
intent.putParcelableArrayListExtra(MovieDetail.EXTRA_MOVIE, movies);
startActivity(intent);
}
});
}
#Override
public void onClick(View v) {
}
private void addItem(){
ArrayList<Film> films = new ArrayList<>();
for (int i = 0; i < dataNama.length; i++){
Film film = new Film();
film.setFilm(dataPhoto.getResourceId(i, -1));
film.setNama(dataNama[i]);
film.setDeskripsi(dataDeskrip[i]);
films.add(film);
}
adapter.setFilms(films);
}
private void prepare(){
dataNama = getResources().getStringArray(R.array.data_film);
dataDeskrip = getResources().getStringArray(R.array.data_deskripsi);
dataPhoto = getResources().obtainTypedArray(R.array.data_foto);
}
}
mainactivity.java

You need to initialize the ArrayList<> first.
ArrayList<Film> film = new ArrayList<>();
film = this.getIntent().getParcelableArrayListExtra(EXTRA_MOVIE);
Then you can access it's value
txt_name = film.get(0).getName();
tvName.setText(txt_name);

Related

How can i randomize question in a quiz app

I made a simple quiz on Android Studio which contains 3+ questions. How to make the questions become random without duplicated. This app does not use a database. I'm new to programming so I don't know what to do about this
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView totalQuestionsTextView;
TextView questionTextView;
Button ansA,ansB,ansC,ansD;
Button submitBtn;
int score=0;
int totalQuestions = QuestionAnswer.question.length;
int currentQuestionIndex = 0;
String selectedAnswer = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
totalQuestionsTextView = findViewById(R.id.total_questions);
questionTextView = findViewById(R.id.question);
ansA = findViewById(R.id.ans_A);
ansB = findViewById(R.id.ans_B);
ansC = findViewById(R.id.ans_C);
ansD = findViewById(R.id.ans_D);
submitBtn = findViewById(R.id.submbit_btn);
ansA.setOnClickListener(this);
ansB.setOnClickListener(this);
ansC.setOnClickListener(this);
ansD.setOnClickListener(this);
submitBtn.setOnClickListener(this);
totalQuestionsTextView.setText("Total Questions : "+totalQuestions);
loadNewQuestion();
}
#Override
public void onClick(View view) {
ansA.setBackgroundColor(Color.WHITE);
ansB.setBackgroundColor(Color.WHITE);
ansC.setBackgroundColor(Color.WHITE);
ansD.setBackgroundColor(Color.WHITE);
Button clickedButton = (Button) view;
if(clickedButton.getId()==R.id.submbit_btn){
currentQuestionIndex++;
loadNewQuestion();
}else{
//choices button clicked
selectedAnswer = clickedButton.getText().toString();
clickedButton.setBackgroundColor(Color.MAGENTA);
}
}
void loadNewQuestion(){
if(currentQuestionIndex == totalQuestions){
finishQuiz();
return;
}
questionTextView.setText(QuestionAnswer.question[currentQuestionIndex]);
ansA.setText(QuestionAnswer.choices[currentQuestionIndex][0]);
ansB.setText(QuestionAnswer.choices[currentQuestionIndex][1]);
ansC.setText(QuestionAnswer.choices[currentQuestionIndex][2]);
ansD.setText(QuestionAnswer.choices[currentQuestionIndex][3]);
}
void finishQuiz(){
String passStatus = "";
if (score > totalQuestions*0.60){
passStatus = "Passes";
}else{
passStatus = "Failed";
}
new AlertDialog.Builder(this)
.setTitle(passStatus)
.setMessage("Score is "+score+" out of "+ totalQuestions)
.setPositiveButton("Restart",(dialogInterface, i) -> restartQuiz())
.setCancelable(false)
.show();
}
void restartQuiz(){
score = 0;
currentQuestionIndex = 0;
loadNewQuestion();
}
QuestionAnswer.java
import java.util.Arrays; import java.util.List; import java.util.Random;
public class QuestionAnswer {
public static String[] question = {
"Which company own the android?",
"Which one is not the programming language?",
"Where are you watching this video"
};
public static String choices[][] = {
{"Google", "Apple", "Nokia", "Samsung"},
{"Java", "Kotlin", "Notepad", "Python"},
{"Facebook", "Whatsapp", "Instagram", "Youtube"},
};
public static String correctAnswers[] = {
"Google",
"Notepad",
"Youtube"
};
}
how can i add shuffle.collection or random to make my app show random question instead
You need to find out about Random class first in Java. Thereafter, you will create a random number using Random class in onClick function, then set a question's index to your Random number

Accessing another activity's method

I have a medicine_activity class
package com.example.shubhmgajra.medikit;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class Medicine_Activity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "Medicine_Activity";
private Button btnAdd;
private ListView listMeds;
private AppDatabase db;
private ArrayAdapter<MedicineRecord> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine);
btnAdd = findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
listMeds = findViewById(R.id.listMeds);
listMeds.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MedicineRecord medicineRecord = db.medicineRecordDao().findMedicineById(id + 1);
Intent intent = new Intent(getApplicationContext(), MedicineInputActivity.class);
startActivity(intent);
MedicineInputActivity.getInstance().update(medicineRecord, true);
}
});
db = AppDatabase.getInstance(getApplicationContext());
FeedAdapter feedAdapter = new FeedAdapter(Medicine_Activity.this, R.layout.list_record, db.medicineRecordDao().loadAllRecords());
listMeds.setAdapter(feedAdapter);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onClick(View v) {
Intent intent = new Intent(this, MedicineInputActivity.class);
startActivity(intent);
}
}
In this i am trying to call update() method of another activity namely MedicineInputActivity
package com.example.shubhmgajra.medikit;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
public class MedicineInputActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MedicineInputActivity";
static EditText dosage;
static EditText medName;
static TimePicker timePicker;
static Button btnSave;
Button btnInc;
Button btnDec;
private AppDatabase db;
private static MedicineInputActivity instance;
boolean isEdit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine_input);
isEdit = false;
instance = this;
dosage = findViewById(R.id.dosage);
dosage.setShowSoftInputOnFocus(false);
dosage.setCursorVisible(false);
medName = findViewById(R.id.medName);
timePicker = findViewById(R.id.simpleTimePicker);
btnInc = findViewById(R.id.btnInc);
btnDec = findViewById(R.id.btnDec);
btnInc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = dosage.getText().toString();
int tempVal = Integer.parseInt(val);
tempVal++;
dosage.setText("" + tempVal);
}
});
btnDec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = dosage.getText().toString();
int tempVal = Integer.parseInt(val);
if (tempVal > 0) {
tempVal--;
}
dosage.setText("" + tempVal);
}
});
btnSave = findViewById(R.id.btnSave);
btnSave.setOnClickListener(this);
db = AppDatabase.getInstance(getApplicationContext());
}
#Override
public void onClick(View v) {
String name = medName.getText().toString();
int min = timePicker.getMinute();
int hour = timePicker.getHour();
String val = dosage.getText().toString();
int dose = Integer.parseInt(val);
MedicineRecord medicineRecord = new MedicineRecord(name, dose, min, hour);
if (validate(name)) {
if (isEdit) {
db.medicineRecordDao().updateRecord(medicineRecord);
} else {
db.medicineRecordDao().insertRecord(medicineRecord);
}
Intent intent = new Intent(this, Medicine_Activity.class);
startActivity(intent);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "Medicine name cannot be empty", Toast.LENGTH_SHORT);
toast.show();
}
}
private boolean validate(String name) {
if (name.length() == 0) {
return false;
} else {
return true;
}
}
public static MedicineInputActivity getInstance() {
return instance;
}
public void update(MedicineRecord medicineRecord, boolean isEdit) {
this.isEdit = isEdit;
dosage.setText(medicineRecord.getDosage());
medName.setText(medicineRecord.getMedName());
timePicker.setHour(medicineRecord.getHour());
timePicker.setMinute(medicineRecord.getMinute());
}
}
What i am trying to achieve is when the user taps the list item, the input activity is loaded and the user can update the record. I wasnt able to find an elegant solution other than making an update method in MedicineInputActivity and then getting an instance of MedicineInputActivity in Medicine_Activity and calling update.
I am getting errors like "Attempt to invoke virtual method 'void com.example.shubhmgajra.medikit.MedicineInputActivity.update() on a null object reference".
You can return data from second activity to the first activity when user is done updating the record. You should start second activity by calling startActivityForResult() instead of startActivity() in the first activity. You should also override onActivityResult() in the first activity. You can read more here.
UPDATE:
I think you want to send selected medicine details from Medicine_Activity to MedicineInputActivity. In that case, you can send selected medicine object by binding it to the intent as follows:
public class Medicine_Activity ... {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
listMeds.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MedicineRecord medicineRecord = db.medicineRecordDao().findMedicineById(id + 1);
Intent intent = new Intent(getApplicationContext(), MedicineInputActivity.class);
intent.putExtra("selectedMedicine", medicineRecord);
startActivity(intent);
MedicineInputActivity.getInstance().update(medicineRecord, true);
}
});
...
}
}
Then on MedicineInputActivity, you should be doing this:
public class MedicineInputActivity ... {
MedicineRecord selectedMedicineRecord;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
selectedMedicineRecord = (MedicineRecord) getIntent().getParcelableExtra("selectedMedicine");
...
}
}
To be able to do this, your MedicineRecord class should implement Parcelable interface.

Array overwrites instead of adding

Good afternoon,
I'm still a beginner in programming, currently learning Android.
I am making a screen that captures some information from a website and moves to a list view. The code below works when I use only the main page of the site, when I try to move to page 2 instead of adding to the end of the Array, it overwrites the entire Array.
I have reached the limit of my knowledge, I can kick it a silly mistake in how they are built, but I could not reach the solution alone.
I'm sorry if I have any typos, I'm using a translator.
package br.com.testejsoup.eu.testejsoup;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private ListView conteudo;
String[] aniNomes;
String[] aniLinks;
ArrayAdapter<String> adaptador;
Document doc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
conteudo = findViewById(R.id.html_conteudo);
new doit().execute();
conteudo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int posicao = position;
Intent intent = new Intent(MainActivity.this, Episodio.class);
intent.putExtra("aniLinks", aniLinks[posicao]);
//Toast.makeText(getApplicationContext(), aniLinks[posicao], Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
public class doit extends AsyncTask<Void, Void, Void>{
String URL = "http://www.URL.com/lancamentos?page=";
String nomeExp;
Elements nome;
Elements links;
int paginas = 5;
#Override
protected Void doInBackground(Void... voids) {
try {
for (int i=1; i<= paginas;i++) {
String new_URL = URL + i;
doc = Jsoup.connect(new_URL).get();
nome = doc.select("div.nome-thumb a.tt");
links = doc.select("div.nome-thumb a.tt");
aniNomes = new String[nome.size()];
aniLinks = new String[links.size()];
for(Element nomeTemp : nome){
nomeExp = nomeTemp.text();
adaptador.add(nomeExp);
}
}
for (int i = 0; i < nome.size(); i++) {
aniNomes[i] = nome.get(i).text();
}
for (int i = 0; i < links.size(); i++) {
aniLinks[i] = links.get(i).attr("abs:HREF");
}
adaptador = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, aniNomes);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
conteudo.setAdapter(adaptador);
}
}
}
New code after the proposed modification.
THANKS FOR THE HELP!!!
package br.com.testejsoup.eu.testejsoup;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ListView conteudo;
ArrayList<String> aniNomes = new ArrayList<>();
ArrayList<String> aniLinks = new ArrayList<>();
ArrayAdapter<String> adaptador;
Document doc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
conteudo = findViewById(R.id.html_conteudo);
new doit().execute();
conteudo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int posicao = position;
Intent intent = new Intent(MainActivity.this, Episodio.class);
intent.putExtra("aniLinks", aniLinks.get(position));
//Toast.makeText(getApplicationContext(), aniLinks[posicao], Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
public class doit extends AsyncTask<Void, Void, Void>{
String URL = "http://www.URL.com/lancamentos?page=";
String nomeExp;
Elements nome;
Elements links;
int paginas = 5;
#Override
protected Void doInBackground(Void... voids) {
try {
for (int i=1; i<= paginas;i++) {
String new_URL = URL + i;
doc = Jsoup.connect(new_URL).get();
nome = doc.select("div.nome-thumb a.tt");
links = doc.select("div.nome-thumb a.tt");
for (Element nomeT : nome){
aniNomes.add(nomeT.text());
}
for (Element linkT : links){
aniLinks.add(linkT.attr("abs:HREF"));
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adaptador = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, aniNomes);
conteudo.setAdapter(adaptador);
}
}
}
Its because you're creating a new adapter in your asynctask and then in your onPostExecute method you're calling setAdapter which swaps out the old adapter and its entries with the new adapter and its new entries.
Rather than creating a new adapter in your asynctask I would just create an array/arraylist, add the new entries to it and then in your onPostExecute just append the entries from this array/list into the one and only adapter entry set.

LinkedList toArray causes crash

Everytime I tried to run these code the program crashed then I tried to get an Array of Objects from my LinkedList.
Product[] arr = (Product[])produktliste.toArray(); causes the crash
This is the source of the MainActivity:
package at.lamprechtdominik.myfirstlistapp;
import java.util.LinkedList;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;
public class MainActivity extends Activity {
public static LinkedList<Product> produktliste = new LinkedList<Product>();
private Button benutzerAnlegen;
private Button listeAnzeigen;
private EditText nameProdukt;
private EditText preisProdukt;
private CheckBox istVorhanden;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
benutzerAnlegen = (Button) findViewById(R.id.btBenutzerAnlegen);
nameProdukt = (EditText) findViewById(R.id.etProduktname);
preisProdukt = (EditText) findViewById(R.id.etPreis);
istVorhanden = (CheckBox) findViewById(R.id.cbProduktVorhanden);
listeAnzeigen = (Button) findViewById(R.id.btZeigeListe);
benutzerAnlegen.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
produktliste.add(neuesProduktAnlegen());
Toast.makeText(getBaseContext(), R.string.anlegen_erfolgreich, Toast.LENGTH_LONG).show();
}
});
listeAnzeigen.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Intent i = new Intent(getBaseContext(), Produktauflistung.class);
//startActivity(i);
Product[] arr = (Product[])produktliste.toArray();
}
});
}
private Product neuesProduktAnlegen(){
String name = nameProdukt.toString();
Double preis = Double.parseDouble(preisProdukt.getText().toString());
boolean vorhanden;
if(istVorhanden.isChecked()){
vorhanden = true;
} else {
vorhanden = false;
}
Product neuesProdukt = new Product(name, preis , vorhanden);
return(neuesProdukt);
}
}
class file Product:
package at.lamprechtdominik.myfirstlistapp;
public class Product {
private String name;
private Double preis;
private boolean istVorhanden;
public Product(String name, Double preis, boolean istVorhanden){
this.name = name;
this.preis = preis;
this.istVorhanden = istVorhanden;
}
public String getName(){
return(name);
}
public Double getPreis(){
return(preis);
}
public boolean getIstVorhanden(){
return(istVorhanden);
}
}
Does anyone know how what i did wrong?
Thanks for your help.
You cannot simply cast the result of toArray() to a Product[] array.
Use this:
Product[] meineProdukte = new Product(produktliste.size());
meineProdukte = produktliste.toArray(meineProdukte);
Try to change to
Product[] arr = produktliste.toArray(new Product[produktliste.size()]);

Android: Is there another way to display data from a string array?

I am trying to display the steps to a recipe, the recipe is stored in a string array.
Im trying to get each step to be inserted into a text view, and have the following code:
public class MethodActivity extends ListActivity{
ListView recipes;
Intent myIntent;
String value;
TextView editvalue;
Intent intent;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipemethod);
editvalue = (TextView)findViewById(R.id.method);
value = getIntent().getStringExtra("searchValue");
editvalue.setText(value);
final String[] words = getResources().getStringArray(R.array.Lasagna);
final TextView tw=(TextView)findViewById(R.id.method);
for(int item = 0;item<words.length;item++){
tw.setText(words [item]);
}
}
}
I am also wanting to make it dynamic so does anyone know how I can do that? (e.g. depending on what the user clicked that recipe is shown).
Thanks
It might be easier to actually use your ListActivity's ListView... You can even show your recipe in another ListView, as it will undoubtedly be more intuitive for the user...
A simple code that does this would go somewhat in the following lines:
File 1: RecipeListActivity.java (shows list of recipes)
package com.epichorns.testproject;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class RecipeListActivity extends ListActivity {
final Recipe[] mRecipesArray = { new Recipe("Lasagna", new String[]{"Some lasagna noodles", "Some tomato sauce"}),
new Recipe("PortalCake", new String[]{"GlaDOS' wit","Is a lie"}),
new Recipe("EarthDestruction", new String[]{"Asteroid", "Kinetic energy"})};
public class Recipe{
public String name;
public String[] steps;
Recipe(String name, String[] steps){
this.name = name;
this.steps = steps;
}
}
public ArrayList<String> FetchRecipesRawArray(Recipe[] recipes){
ArrayList<String> ret = new ArrayList<String>();
for(int i=0;i<recipes.length;i++){
ret.add(recipes[i].name);
}
return ret;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, FetchRecipesRawArray(mRecipesArray));
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
Intent intent = new Intent(this, RecipeActivity.class);
intent.putExtra(RecipeActivity.EXTRA_RECIPEARRAY, mRecipesArray[position].steps);
startActivity(intent);
}
}
File 2: RecipeActivity.java (shows a recipe in a list)
package com.epichorns.testproject;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class RecipeActivity extends ListActivity {
final static public String EXTRA_RECIPEARRAY = "recipeArray";
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String[] recipeArray = getIntent().getStringArrayExtra(EXTRA_RECIPEARRAY);
if(recipeArray!=null){
if(recipeArray.length>0){
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, recipeArray);
setListAdapter(adapter);
}
}
}
}
Alternately, here is a code which composites a TextView below the recipes list in order to show the recipe content without opening another Activity:
File: RecipeListActivity.java
package com.epichorns.testproject;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class RecipeListActivity extends ListActivity {
final Recipe[] mRecipesArray = { new Recipe("Lasagna", new String[]{"Some lasagna noodles", "Some tomato sauce"}),
new Recipe("PortalCake", new String[]{"GlaDOS' wit","Is a lie"}),
new Recipe("EarthDestruction", new String[]{"Asteroid", "Kinetic energy"})};
TextView mTextView_recipeTitle;
TextView mTextView_recipe;
public class Recipe{
public String name;
public String[] steps;
Recipe(String name, String[] steps){
this.name = name;
this.steps = steps;
}
}
public ArrayList<String> FetchRecipesRawArray(Recipe[] recipes){
ArrayList<String> ret = new ArrayList<String>();
for(int i=0;i<recipes.length;i++){
ret.add(recipes[i].name);
}
return ret;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView_recipe = (TextView)findViewById(R.id.recipeText);
mTextView_recipeTitle = (TextView)findViewById(R.id.recipeTitle);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, FetchRecipesRawArray(mRecipesArray));
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
mTextView_recipeTitle.setText(mRecipesArray[position].name);
mTextView_recipe.setText("");
String[] recipeSteps = mRecipesArray[position].steps;
for(int i=0;i<recipeSteps.length;i++){
mTextView_recipe.append(recipeSteps[i]+"\n");
}
}
}
File: main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:background="#400000FF"
/>
<TextView
android:id="#+id/recipeTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#4000FF00"
/>
<TextView
android:id="#+id/recipeText"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#40FF0000"
/>
</LinearLayout>
You will want to use tw.append() instead of setText, otherwise all you will ever see is the last string in the array.
Make it dynamic, I would use a fragments (using the Android Support Library if on older android versions) model, load each array, attaching the string array as a bundle to the fragment before launching.
Fragment tut:http://developer.android.com/guide/topics/fundamentals/fragments.html
Support library: http://developer.android.com/training/basics/fragments/support-lib.html

Categories

Resources