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()]);
Related
I want to create a way which will add item to cart by creating a child cart the in that child it will retrieve current username and then under that it will save all the details of added item
this is the code of the fragment in which cart button is available (course = description,email = price,purl = url of image)
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
public class descfragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
String name, course, email, purl;
public descfragment() {
}
public descfragment(String name, String course, String email, String purl) {
this.name = name;
this.course = course;
this.email = email;
this.purl = purl;
}
public static descfragment newInstance(String param1, String param2) {
descfragment fragment = new descfragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_descfragment, container, false);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AppCompatActivity activity =(AppCompatActivity)getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.wrapper,new recfragment()).addToBackStack(null).commit();
}
});
ImageView imageholder = view.findViewById(R.id.imageholder);
TextView nameholder = view.findViewById(R.id.nameholder);
TextView courseholder = view.findViewById(R.id.courseholder);
TextView emailholder = view.findViewById(R.id.emailholder);
Button cart = view.findViewById(R.id.cartt);
TextView addItem = view.findViewById(R.id.addIteam);
TextView removeItem = view.findViewById(R.id.removeItem);
TextView quantity = view.findViewById(R.id.quantity);
final int[] totalquantity = {1};
nameholder.setText(name);
courseholder.setText(course);
emailholder.setText(email);
if (imageholder != null) {
Glide.with(getContext()).load(purl).into(imageholder);
}
Glide.with(getContext()).load(purl).into(imageholder);
//changing static getemail to int type
//for openig cart
//setting click on textview for increasing the quantity
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(totalquantity[0] < 10){
totalquantity[0]++;
quantity.setText(String.valueOf(totalquantity[0]));
}
}
});
removeItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(totalquantity[0] > 1) {
totalquantity[0]--;
quantity.setText(String.valueOf(totalquantity[0]));
}
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener((v, keyCode, event) -> {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
AppCompatActivity activity = (AppCompatActivity) getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.wrapper, new recfragment()).addToBackStack(null).commit();
return true;
}
return false;
});
}
}
this is the register activity code in this activity we have the username which needed to be retirived
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.foodcourt.MainActivity;
import com.example.foodcourt.R;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class register extends AppCompatActivity {
Button button5;
//create obj of Databaserefrence to access firebase RealTime Database
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl("https://url of firebase database/");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final TextInputLayout nameLayout = findViewById(R.id.Name);
final TextInputLayout phoneLayout = findViewById(R.id.phone);
final TextInputLayout passwordLayout = findViewById(R.id.password);
final TextInputLayout repassLayout = findViewById(R.id.repass);
final Button signup = findViewById(R.id.sign);
final EditText name = nameLayout.getEditText();
final EditText phone = phoneLayout.getEditText();
final EditText password = passwordLayout.getEditText();
final EditText repass = repassLayout.getEditText();
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//get data from editTexts into string
final String nameTxt = name.getText().toString();
final String phoneTxt = phone.getText().toString();
final String passwordTxt = password.getText().toString();
final String repassTxt = repass.getText().toString();
//Check if user filled all details before sending data to firebase
if (nameTxt.isEmpty() || phoneTxt.isEmpty() || passwordTxt.isEmpty() || repassTxt.isEmpty()) {
Toast.makeText(register.this, "Please fill all fields", Toast.LENGTH_SHORT).show();
}
//check if pass are matching
else if (!passwordTxt.equals(repassTxt)) {
Toast.makeText(register.this, "PASSWORDS ARE NOT MATCHING", Toast.LENGTH_SHORT).show();
} else {
databaseReference.child("users").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
//check if phone number is registered before \
if (snapshot.hasChild(phoneTxt)) {
Toast.makeText(register.this, "Already registered", Toast.LENGTH_SHORT).show();
} else {
//sending data to Firebase
//using phoneNumbers
databaseReference.child("users").child(phoneTxt).child("name").setValue(nameTxt);
databaseReference.child("users").child(phoneTxt).child("phone").setValue(phoneTxt);
databaseReference.child("users").child(phoneTxt).child("password").setValue(passwordTxt);
Toast.makeText(register.this, "REGISTERED SUCCESFULLY", Toast.LENGTH_SHORT).show();
startActivity(new Intent(register.this, MainActivity.class));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
});
}
}
I followed some tutorials but they were for firestore.
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
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);
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.
In my project i several onClick listeners, and all of them are fine, but one, i can not find and error in the code, if i delete the code and retype it and save it, it is fine without errors, if i close and eclipse and comeback later, variable cant be resolved again.
This is where it cant be resolved in the code:
Button webButton = (Button) newStockRow.findViewById(R.id.webButton);
webButton.setOnClickListener(getStockFromWebClickListener);
and this is how i create it:
public OnClickListener getStockFromWebClickListener = new OnClickListener(){
#Override
public void onClick(View arg0) {
TableRow tableR = (TableRow) arg0.getParent();
TextView stock = (TextView) tableR.findViewById(R.id.stockSymbolTextView);
String stockSymbol = stock.getText().toString();
String stockURL = getString(R.string.yahoo_stock_url) + stockSymbol;
Intent getStockWebPage = new Intent(Intent.ACTION_VIEW, Uri.parse(stockURL));
startActivity(getStockWebPage);
}
};
Code for full File:
package com.gscore.quotestock;
import java.util.Arrays;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class StockQ extends Activity {
public final static String STOCK_SYMBOL = "com.gscore.quotestock.STOCK";
private SharedPreferences stockSymbolsEntered;
private TableLayout stockTableScrollView;
private EditText stockSymbolET;
Button enterStockSymbolButton;
Button deleteStocksButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stock_q);
// Get user stock list
stockSymbolsEntered = getSharedPreferences("stockList", MODE_PRIVATE);
// Initialize UI components
stockTableScrollView = (TableLayout) findViewById(R.id.stockTableLayout);
stockSymbolET = (EditText) findViewById(R.id.stockSymbolEditText);
enterStockSymbolButton= (Button) findViewById(R.id.enterButton);
deleteStocksButton= (Button) findViewById(R.id.deleteAllButton);
// Set ClickListeners
enterStockSymbolButton.setOnClickListener(enterButtonClickListener);
deleteStocksButton.setOnClickListener(deleteButtonClickListener);
updateSavedStockList(null);
}
private void updateSavedStockList(String newStockSymbol){
String[] stocks = stockSymbolsEntered.getAll().keySet().toArray(new String[0]);
Arrays.sort(stocks, String.CASE_INSENSITIVE_ORDER);
if (newStockSymbol != null){
insertStockInStockTable(newStockSymbol, Arrays.binarySearch(stocks, newStockSymbol));
} else {
for(int i = 0; i < stocks.length; i++){
insertStockInStockTable(stocks[i], i);
}
}
}
private void saveStockSymbol(String newStock){
String isTheStockNew = stockSymbolsEntered.getString(newStock, null);
SharedPreferences.Editor preferencesEditor = stockSymbolsEntered.edit();
preferencesEditor.putString(newStock, newStock);
preferencesEditor.commit();
if(isTheStockNew == null){
updateSavedStockList(newStock);
}
}
private void insertStockInStockTable(String stock, int arrayIndex){
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View newStockRow = inflater.inflate(R.layout.stock_quote_row, null);
TextView newStockTextView = (TextView) newStockRow.findViewById(R.id.stockSymbolTextView);
newStockTextView.setText(stock);
Button stockQuoteButton = (Button) newStockRow.findViewById(R.id.stockQuoteButton);
stockQuoteButton.setOnClickListener(getStockActivityListener);
Button webButton = (Button) newStockRow.findViewById(R.id.webButton);
webButton.setOnClickListener(getStockFromWebClickListener);
stockTableScrollView.addView(newStockRow, arrayIndex);
}
public OnClickListener enterButtonClickListener= new OnClickListener(){
#Override
public void onClick(View v) {
if(stockSymbolET.getText().length() > 0){
saveStockSymbol(stockSymbolET.getText().toString());
stockSymbolET.setText("");
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(stockSymbolET.getWindowToken(), 0);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(StockQ.this);
builder.setTitle(R.string.invalid_stock_symbol);
builder.setPositiveButton(R.string.ok, null);
builder.setMessage(R.string.missing_stock_symbol);
AlertDialog theAlertDialog = builder.create();
theAlertDialog.show();
}
}
};
private void deleteAllStocks(){
stockTableScrollView.removeAllViews();
}
public OnClickListener deleteButtonClickListener = new OnClickListener(){
#Override
public void onClick(View v) {
deleteAllStocks();
SharedPreferences.Editor preferencesEditor = stockSymbolsEntered.edit();
preferencesEditor.clear();
preferencesEditor.commit();
}
};
public OnClickListener getStockActivityListener = new OnClickListener(){
#Override
public void onClick(View v) {
TableRow tableR = (TableRow) v.getParent();
TextView stock = (TextView) tableR.findViewById(R.id.stockSymbolTextView);
String stockSymbol = stock.getText().toString();
Intent intent = new Intent(StockQ.this, StockInfoActivity.class);
intent.putExtra(STOCK_SYMBOL, stockSymbol);
startActivity(intent);
}
};
public OnClickListener getStockFromWebClickListener = new OnClickListener(){
#Override
public void onClick(View arg0) {
TableRow tableR = (TableRow) arg0.getParent();
TextView stock = (TextView) tableR.findViewById(R.id.stockSymbolTextView);
String stockSymbol = stock.getText().toString();
String stockURL = getString(R.string.yahoo_stock_url) + stockSymbol;
Intent getStockWebPage = new Intent(Intent.ACTION_VIEW, Uri.parse(stockURL));
startActivity(getStockWebPage);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.stock_q, menu);
return true;
}
}
That's indeed an annoying problem with importing an inner class (or interface) on Eclipse.
What you have to do is instead of:
new OnClickListener()
Write:
new View.OnClickListener()
And make sure that android.view.View is imported.