I am very new to android development and I was following Stanford CS193A lectures to learn something. While trying to create dictionary(without using stand-ford library), i feel like I did most of the things right but I am not able to launch app on phone. Here my java code. Please help me.
package com.hfad.dictionarytwo;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;
public class MainActivity extends AppCompatActivity {
private HashMap<String, String> dictionary;
private ArrayList<String> list;
private ArrayAdapter<String> adapter;
private ArrayList<String> fiveDefns;
#Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dictionary = new HashMap<String,String>();
list = new ArrayList<String>();
fiveDefns = new ArrayList<String>();
readWordsFromFile();
pickRandomWords();
}
private void readWordsFromFile(){
Scanner scan = new Scanner(getResources().openRawResource(R.raw.grewords));
//following delimator is for spliting at tab
while (scan.hasNextLine()){
String line = scan.nextLine();
String[] parts = line.split("\t");
if (parts.length >= 2){
String word = parts[0];
String defn = parts[1];
list.add(word);
dictionary.put(word,defn);
}
}
}
private void pickRandomWords() {
//folowing code shuffles all the words and takes the first three words
ArrayList<String> threeWords = new ArrayList<String>();
Collections.shuffle(list);
for (int i = 0; i < 5; i++) {
threeWords.add(list.get(i));
}
//display the first word, after shuffling ofcourse
final String theWord = threeWords.get(0);
TextView theWordView = findViewById(R.id.the_word);
theWordView.setText(theWord);
fiveDefns.clear();
for (String word : threeWords) {
fiveDefns.add(dictionary.get(word));
}
//shuffle it again
Collections.shuffle(fiveDefns);
//make adapter to show three definitions on screen
if (adapter == null) {
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, fiveDefns);
} else {
adapter.notifyDataSetChanged();
}
ListView listView = findViewById(R.id.word_list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//get the posiiton of definition user clicked from threeDefn arraylist
String defnClicked = (String) fiveDefns.get(position);
//want to know if it is right definition
String rightAnswer = dictionary.get(theWord);
if (defnClicked.equals(rightAnswer)) {
//note that just 'this' will not work b/c we want to refer to over all activity
//not this little activity, which is small activity inside overall activity
Toast.makeText(MainActivity.this, "You are awesome", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "You Suck", Toast.LENGTH_SHORT).show();
}
pickRandomWords();
}
});
}
}
I have grewords txt file in my res directory .
In your activity change condition in readWordsFromFile() and call pickRandomWords() from readWordsFromFile().
See the below code.
Make sure that your file has content like :
abcd kolkata valsad
123 auto vapi
789 neha palghar
klj ma ghfgh
mnk fgdgdf papa
Note: In your text file data should be in the above format.because you split words using space("\t").
public class MainActivity extends AppCompatActivity {
private HashMap<String, String> dictionary;
private ArrayList<String> list;
private ArrayAdapter<String> adapter;
private ArrayList<String> fiveDefns;
#Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dictionary = new HashMap<String,String>();
list = new ArrayList<String>();
fiveDefns = new ArrayList<String>();
readWordsFromFile();
}
private void readWordsFromFile(){
Scanner scan = new Scanner(getResources().openRawResource(R.raw.grewords));
//following delimator is for spliting at tab
while (scan.hasNextLine()){
String line = scan.nextLine();
if(line.contains(" ")) {
String[] parts = line.split(" ");
if (parts.length >= 1) {
String word = parts[0];
String defn = parts[1];
list.add(word);
dictionary.put(word, defn);
}
}
}
pickRandomWords();
}
private void pickRandomWords() {
//folowing code shuffles all the words and takes the first three words
ArrayList<String> threeWords = new ArrayList<String>();
Collections.shuffle(list);
for (int i = 0; i < 3; i++) {
threeWords.add(list.get(i));
}
//display the first word, after shuffling ofcourse
final String theWord = threeWords.get(0);
TextView theWordView = findViewById(R.id.the_word);
theWordView.setText(theWord);
fiveDefns.clear();
for (String word : threeWords) {
fiveDefns.add(dictionary.get(word));
}
//shuffle it again
Collections.shuffle(fiveDefns);
//make adapter to show three definitions on screen
if (adapter == null) {
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, fiveDefns);
} else {
adapter.notifyDataSetChanged();
}
ListView listView = findViewById(R.id.word_list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//get the posiiton of definition user clicked from threeDefn arraylist
String defnClicked = (String) fiveDefns.get(position);
//want to know if it is right definition
String rightAnswer = dictionary.get(theWord);
if (defnClicked.equals(rightAnswer)) {
//note that just 'this' will not work b/c we want to refer to over all activity
//not this little activity, which is small activity inside overall activity
Toast.makeText(MainActivity.this, "You are awesome", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "You Suck", Toast.LENGTH_SHORT).show();
}
pickRandomWords();
}
});
}
}
** Note:** you just replace the above code in your file.
Related
I have Activity that shows only listview (He pulls the data from SQLite database), There is no limit for the data he can shows, and it work out well.
Now, I want to add a new little listview to the MainActivity which will show only the last five of the data.
I could not find anywhere on the network how to do it..
DataListActivity.java
package com.example.ido.grades;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class DataListActivity extends ActionBarActivity {
ListView listView;
SQLiteDatabase sqLiteDatabase;
CourseDbHelper courseDbHelper;
Cursor cursor;
ListDataAdaptar listDataAdaptar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.update_course);
hideActionBar();
listView = (ListView) findViewById(R.id.list_view);
listDataAdaptar = new ListDataAdaptar(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(listDataAdaptar);
registerForContextMenu(listView);
courseDbHelper = new CourseDbHelper(getApplicationContext());
sqLiteDatabase = courseDbHelper.getReadableDatabase();
cursor = courseDbHelper.getInformation(sqLiteDatabase);
registerForContextMenu(listView);
if (!cursor.moveToFirst()){
}
else {
do {
String year,semester,course,points,grade;
year = cursor.getString(0);
semester = cursor.getString(1);
course = cursor.getString(2);
points = cursor.getString(3);
grade = cursor.getString(4);
DataProvider dataProvider = new DataProvider(year,semester,course,points,grade);
listDataAdaptar.add(dataProvider);
}
while (cursor.moveToNext());
}
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_data_list, menu);
}
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int mySelectedRowIndex = info.position;
switch (item.getItemId()) {
case R.id.update_item:
courseDbHelper = new CourseDbHelper(getApplicationContext());
sqLiteDatabase = courseDbHelper.getReadableDatabase();
DataProvider raw2 = (DataProvider)listDataAdaptar.getItem(mySelectedRowIndex);
Intent i = new Intent(DataListActivity.this, UpdateCourseActivity.class);
String year = raw2.getYear();
String semester = raw2.getSemester();
String course = raw2.getCourse();
String points = raw2.getPoints();
String grade = raw2.getGrade();
int semIndex;
if (semester.equals("A'")){
semIndex =1;
}
else if (semester.equals("B'")){
semIndex =2;
}
else{
semIndex=3;
}
i.putExtra("YEAR", year);
i.putExtra("SEMESTER", Integer.toString(semIndex));
i.putExtra("COURSE", course);
i.putExtra("POINTS", points);
i.putExtra("GRADE", grade);
i.putExtra("POS", Integer.toString(mySelectedRowIndex));
startActivity(i);
return true;
case R.id.delete_item:
courseDbHelper = new CourseDbHelper(getApplicationContext());
sqLiteDatabase = courseDbHelper.getReadableDatabase();
DataProvider raw = (DataProvider)listDataAdaptar.getItem(mySelectedRowIndex);
courseDbHelper.deleteInformation(raw.getYear(), raw.getSemester(), raw.getCourse(), raw.getPoints(), raw.getGrade());
Toast.makeText(this,"delete, pos["+mySelectedRowIndex+"]",Toast.LENGTH_LONG).show();
finish();
startActivity(getIntent());
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onBackPressed() {
startActivity(new Intent(this, MainActivity.class));
}
private void hideActionBar() {
//Hide the action bar only if it exists
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
}
}
ListDataAdapter.java
package com.example.ido.grades;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ido on 08/08/2015.
*/
public class ListDataAdaptar extends ArrayAdapter{
List list = new ArrayList();
public ListDataAdaptar(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler{
TextView YEAR,SEMESTER,COURSE,POINTS,GRADE;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.YEAR = (TextView)row.findViewById(R.id.textYear);
layoutHandler.SEMESTER = (TextView)row.findViewById(R.id.textSemester);
layoutHandler.COURSE = (TextView)row.findViewById(R.id.textCourse);
layoutHandler.POINTS = (TextView)row.findViewById(R.id.textPoints);
layoutHandler.GRADE = (TextView)row.findViewById(R.id.textGrade);
row.setTag(layoutHandler);
}
else{
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider) this.getItem(position);
layoutHandler.YEAR.setText(dataProvider.getYear());
layoutHandler.SEMESTER.setText(dataProvider.getSemester());
layoutHandler.COURSE.setText(dataProvider.getCourse());
layoutHandler.POINTS.setText(dataProvider.getPoints());
layoutHandler.GRADE.setText(dataProvider.getGrade());
return row;
}
}
You can move to the last position of your current cursor and move to previous rows getting required data. Sort of:
ArrayList string;
if (cursor.moveToLast()){
for (int i = 1; i<=6; i++) {
string.add(cursor.getString(cursor.getColumnIndex("your_data")));
cursor.moveToPrevious();
}
}
cursor.close();
The result will be ArrayList with last 6 strings of your cursor data. You can feed it to the new ArrayAdapter and show it on the screen.
Instead of ArrayList you can create another cursor as well with all existing data and feed it to already existing adapter for example as it's described here:
https://stackoverflow.com/a/18290921/4890659
Ignoring your code, you obviously have an Array of Objects your passing into the constructor of your Array Adapter.
Object[] data = new Object[]{...}
MyArrayAdapter myAdapter = new MyArrayAdapter(data ,... else)
You simply get this data array and append the last 6 elements to a new array.
Object[] data2 = new Object[6]
for(int i = data.length()-7; i<data.length(); i++){
data2[data.length()-i] = data[i]
Then create a new Adapter passing the new data2 array.
MyArrayAdapter myAdapter = new MyArrayAdapter(data2, ... else)
Create method that will return the last 6 rows i cursor [SQL query].
cursor = courseDbHelper.getInformationLast_6(sqLiteDatabase);
SQL:
SELECT * FROM table ORDER BY column DESC [ASC] LIMIT 6;
by this you can get 6 items in your list. Try with following code in your adapter class.
public int getCount() {
return 6;
}
than change your query to limit 6 by ascending order or descending order.
I have a table in the database called PrimaryData Which includes fields are PrimaryDataId and PrimaryDataCode .My problem is,When the cursor returns data from database ,Spinner does not set the values of the cursor.
xml spinner file
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="14sp"
android:textColor= "#000000"
android:spinnerMode="dialog" />
PrimaryData class in which to put PrimaryDataId and PrimaryDataCode. This class is the equivalent of a database table.
package com.example.proposaldashborad;
public class PrimeryData {
private int primeryDataId;
private String primeryDataCode;
#Override
public String toString() {
return this.primeryDataCode; // What to display in the Spinner list.
}
public int getPrimaryDataId() {
return primeryDataId;
}
public void setPrimaryDataId(int value) {
this.primeryDataId = value;
}
public int getPrimaryDataCode() {
return primeryDataId;
}
public void setPrimaryDataCode(String value) {
this.primeryDataCode = value;
}
}
this code fill Spinner
private void GetPrimaryDataForSpinner(String primaryDataName, Cursor cr) {
cr.moveToFirst();
//array_spinner = new String[cr.getCount()];
ArrayList<PrimeryData> pds = new ArrayList<PrimeryData>() ;
do {
//array_spinner[i] = cr.getString(cr.getColumnIndex("PrimeryDataCode"));
PrimeryData pd = new PrimeryData() ;
pd.setPrimaryDataId(cr.getInt(cr.getColumnIndex("PrimeryDataId")));
pd.setPrimaryDataCode(cr.getString(cr.getColumnIndex("PrimeryDataCode")));
pds.add(pd) ;
} while (cr.moveToNext());
cr.close();
if (primaryDataName == "Admin") {
adapterAdmin = new ArrayAdapter<PrimeryData>(this,R.layout.spinner, pds);
sAdmin = (Spinner) findViewById(R.id.spinnerAdmin);
sAdmin.setAdapter(adapterAdmin);
}
}
And this is my code when data is returned from the database.
private Spinner sAdmin;
private ArrayAdapter<PrimeryData> adapterAdmin;
db = new DBAdapter(getApplicationContext());
db.open();
cr = db.getViewMT26(entityID);
cr.moveToFirst();
if(cr.getCount()>0) {
PrimeryData pd = new PrimeryData();
pd.setPrimaryDataId(cr.getInt(cr.getColumnIndex("AdminId")));
pd.setPrimaryDataCode(cr.getString(cr.getColumnIndex("Admin")));
sAdmin.setSelection(adapterAdmin.getPosition(pd));
}
cr.close();
db.close();
My main question is why
adapterAdmin.getPosition (pd));
Returns -1?
You have to initialize your adapterAdmin, and set this to your spinner by setAdapter method.
Furthermore, if you only using a list of PrimeryData, then the text which is displayed on each spinner item will be PrimeryData (instance) toString().
Follow this code to set value in Spinner
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity implements OnItemSelectedListener {
Spinner spinnerOsversions;
TextView selVersion;
private String[] state = { "Cupcake", "Donut", "Eclair", "Froyo",
"Gingerbread", "HoneyComb", "IceCream Sandwich", "Jellybean",
"kitkat" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println(state.length);
selVersion = (TextView) findViewById(R.id.selVersion);
spinnerOsversions = (Spinner) findViewById(R.id.osversions);
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, state);
adapter_state
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerOsversions.setAdapter(adapter_state);
spinnerOsversions.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
spinnerOsversions.setSelection(position);
String selState = (String) spinnerOsversions.getSelectedItem();
selVersion.setText("Selected Android OS:" + selState);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
I have this code so far. The Model Spinner automatically populates according to what the user picks for the Manufacture. (For the code below I only have it set up for BMW). Is there any way for the third spinner (Color) to be populated based on the Manufacture and Model.
So if you select BMW on the first spinner and then you select M3 coupe for the second spinner the third spinner would show all the option in the M3_Color Array.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class MainActivity extends Activity implements OnItemSelectedListener {
private String[] Manufacture { "Ford",
"BMW",
"Nissan",
"Toyota",
"Chevy",
};
private String[] BMW_Model = { "128i Coupe",
"M3 Coupe",
"M5 Sedan",
"640i Gran Coupe",
"335i Coupe",
};
private String[] M3_Color = { "Jerez Black Metallic",
"Melbourne Red Metallic",
"Mineral White Metallic",
"Le Mans Blue Metallic",
};
Spinner spinnerManufacture, spinnerModel, spinnerColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinnerManufacture = (Spinner) findViewById(R.id.manufacture_spinner);
ArrayAdapter<String> MaufactureAdapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item,Manufacture);
MaufactureAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerManufacture.setAdapter(MaufactureAdapter);
spinnerManufacture.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {
// TODO Auto-generated method stub
{
if(parent.getId() == R.id.maufacture_spinner && position == 1)
{
spinnerModel = (Spinner) findViewById(R.id.model_spinner);
ArrayAdapter<String> ModelAdapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, BMW_Model);
ModelAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerModel.setAdapter(ModelAdapter);
if(parent.getId() == R.id.model_spinner)
{
String[] Color;
if(spinnerMaufacture.getSelectedItem().toString.equals("BMW"))
{
if(spinnerModel.getSelectedItem().toString.equals("M3 Coupe))
{
Color = M3_Color
}
}
spinnerColor = (Spinner) findViewById(R.id.color_spinner);
ArrayAdapter<String> ColorAdapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, M3_Color);
ColorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerColor.setAdapter(ColorAdapter);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
you need to move if(parent.getId() == R.id.model_spinner) outside if(parent.getId() == R.id.maufacture_spinner then makesure and call spinnerModel.setOnItemSelectedListener(this) onCreate, to do that you need to move spinnerModel = (Spinner) findViewById(R.id.model_spinner) into your on create, I'd recommend doing the same for all your views, that way you don't call findViewById every time you select a spinner item.
EDIT:
Spinner spinnerManufacture, spinnerModel, spinnerColor;
private ArrayAdapter<String> modelAdapter;
private ArrayAdapter<String> maufactureAdapter;
private ArrayAdapter<String> colorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinnerManufacture = (Spinner) findViewById(R.id.manufacture_spinner);
spinnerModel = (Spinner) findViewById(R.id.model_spinner);
spinnerColor = (Spinner) findViewById(R.id.color_spinner);
maufactureAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, Manufacture);
modelAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
colorAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
maufactureAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
modelAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
colorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerColor.setAdapter(colorAdapter);
spinnerManufacture.setAdapter(maufactureAdapter);
spinnerModel.setAdapter(modelAdapter);
spinnerManufacture.setOnItemSelectedListener(this);
spinnerModel.setOnItemSelectedListener(this);
spinnerColor.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.maufacture_spinner) {
String[] model;
if (spinnerManufacture.getSelectedItem().toString().equals("BMW")){
model = BMW_Model;
} else {
model = new String[] {"not sure what model list to use"};
}
modelAdapter.clear();
modelAdapter.addAll(model);
}
if (parent.getId() == R.id.model_spinner) {
String[] Color;
if (spinnerModel.getSelectedItem().toString().equals("M3 Coupe")) {
Color = M3_Color;
} else if (spinnerModel.getSelectedItem().toString().equals("M5 Sedan")) {
Color = M5_Color;
} else {
Color = new String[] { "not sure what color list to use" };
}
colorAdapter.clear();
colorAdapter.addAll(Color);
}
}
this is what I recommend you try.
Just build the string based on what is selected like below. This sets the color list as M3_Color for BMW and M3 Coupe being selected, and M5_Color when BMW and M5 Sedan are selected. This would need to be done for all possible combinations.
if(parent.getId() == R.id.model_spinner)
{
String[] Color = new String[];
if(spinnerManufacture.getSelectedItem().toString().equals("BMW"))
{
if(spinnerModel.getSelectedItem().toString().equals("M3 Coupe"))
{
Color = M3_Color;
}
else if(spinnerModel.getSelectedItem().toString().equals("M5 Sedan"))
{
Color = M5_Color;
}
}
spinnerColor = (Spinner) findViewById(R.id.color_spinner);
ArrayAdapter<String> ColorAdapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, Color);
ColorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerColor.setAdapter(ColorAdapter);
}
I currently have a listview which contains a couple of strings. These are called from a string array in strings.xml
<string name="app_name">Taxi Me</string>
<string-array name="taxi_array">
<item>Barrys Taxi</item>
<item>Boom Taxi</item>
</string-array>
What I was trying to do is create subitems for these so that i can show fields such as address and contact details etc. I made a customlistview a while back but cant work out how I can do it using the strings.xml file? Are there any particular tags I need to use so they show up in the list view?
Main Activity Code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String[] taxi = getResources().getStringArray(R.array.taxi_array);
final String[] address = getResources().getStringArray(R.array.taxi_add);
setListAdapter(new ArrayAdapter<String>(this, R.layout.listtaxi, taxi));
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
for (int i = 0; i < taxi.length; i++) {
lv.add(new ListTaxi (taxi[i], address[i]));
}
/*lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_LONG).show();
}
});
*/
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, final int position, long id)
{
final int selectedPosition = position;
AlertDialog.Builder adb=new AlertDialog.Builder(ListTaxi.this);
adb.setTitle("Taxi Booking");
adb.setMessage("You Have Selected: "+lv.getItemAtPosition(position));
adb.setPositiveButton("Book", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), Booking.class);
intent.putExtra("booking", taxi[selectedPosition]);
startActivity(intent);
}
});
adb.setNegativeButton("Cancel", null);
adb.show();
}
});
EDIT: Okay, just for kicks, I threw this together. It compiles and functions correctly, see if you can adapt it for your particular needs:
layout/taxi_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:padding="10dp"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/taxi_name"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/taxi_address"
/>
</LinearLayout>
layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
TaxiMain.java
package com.test.taxi;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class TaxiMain extends ListActivity {
/** Called when the activity is first created.
* #return */
class Taxi {
private String taxiName;
private String taxiAddress;
public String getName() {
return taxiName;
}
public void setName(String name) {
taxiName = name;
}
public String getAddress() {
return taxiAddress;
}
public void setAddress(String address) {
taxiAddress = address;
}
public Taxi(String name, String address) {
taxiName = name;
taxiAddress = address;
}
}
public class TaxiAdapter extends ArrayAdapter<Taxi> {
private ArrayList<Taxi> items;
private TaxiViewHolder taxiHolder;
private class TaxiViewHolder {
TextView name;
TextView address;
}
public TaxiAdapter(Context context, int tvResId, ArrayList<Taxi> items) {
super(context, tvResId, items);
this.items = items;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.feed_view, null);
taxiHolder = new TaxiViewHolder();
taxiHolder.name = (TextView)v.findViewById(R.id.taxi_name);
taxiHolder.address = (TextView)v.findViewById(R.id.taxi_address);
v.setTag(taxiHolder);
} else taxiHolder = (TaxiViewHolder)v.getTag();
Taxi taxi = items.get(pos);
if (taxi != null) {
taxiHolder.name.setText(taxi.getName());
taxiHolder.address.setText(taxi.getAddress());
}
return v;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] taxiNames = getResources().getStringArray(R.array.taxi_name_array);
String[] taxiAddresses = getResources().getStringArray(R.array.taxi_address_array);
ArrayList<Taxi> taxiList = new ArrayList<Taxi>();
for (int i = 0; i < taxiNames.length; i++) {
taxiList.add(new Taxi(taxiNames[i], taxiAddresses[i]));
}
setListAdapter(new TaxiAdapter(this, R.layout.taxi_list_item, taxiList));
}
}
_____END EDIT_______
You'd probably be better off using a database for something like this, to keep the records tied together. If you're set on using arrays, one thing you could do is make a separate array for each item you need (e.g. taxi_array, taxi_address_array, taxi_phone_array) then make a Taxi object in your code:
class Taxi {
String taxiName;
String taxiAddress;
String taxiPhone;
public Taxi(String name, String address, String phone) {
taxiName = name;
taxiAddress = address;
taxiPhone = phone;
}
}
private List<Taxi> taxiList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] taxiNames = getResources().getStringArray("taxi_array");
String[] taxiAddresses = getResources().getStringArray("taxi_address_array");
String[] taxiPhones = getResources().getStringArray("taxi_phone_array");
taxiList = new ArrayList<Taxi>();
for (int i = 0; i < taxiNames.length; i++) {
taxiList.add(new Taxi(taxiNames[i], taxiAddresses[i], taxiPhones[i]));
}
}
(This is uncompiled code, some tweaks may be needed) But then you'll have a List of Taxi items, containing all of the compiled information from the different arrays. A database would still be a much better option (or even a CSV file with the data, in your assets).
I had same problem and I solved myself like this:
you can simply add subitem like this code and you don't need so much coding!!
<string name="app_name">Taxi Me</string>
<string-array name="taxi_array">
<item>
<item>Barrys Taxi</item>
<item>adress</item>
<item>contact</item>
<item>ANY THING...</item>
</item>
<item>
<item>Boom Taxi</item>
<item>adress</item>
<item>contact</item>
<item>ANY THING...</item>
</item>
</string-array>
Are you looking for some sort of nested Lists?
Have a look at ExpandableListView:
http://developer.android.com/reference/android/widget/ExpandableListView.html
and
http://mylifewithandroid.blogspot.com/2008/05/expandable-lists.html
Excuse me, but i somehow cant post comments for the answers, so i have to write my own here
I need to get String data from custom ListView (consist of EditText and ImageView).
Here is my code:
First, i declare my own copy of ArrayList
private ArrayList<EditText> m_edit = null;
Second, i initialize it inside onCreate method of my Activity
public void onCreate(Bundle savedInstanceState) {
...
m_edit = new ArrayList<EditText>();
...
Third, i fill my ArrayList with EditText copies and then add them to ListView using ArrayAdapter
fieldAddButton.setOnClickListener(new OnClickListener()
{
public void onClick(View view){
EditText et = new EditText(AddCategory.this);
m_edit.add(et);
m_adapter.notifyDataSetChanged();
}
});
Fourth, i want to get EditText value for any item in my custom ListView. So i do something like this:
for (int i = 0;i<m_edit.size();i++){
_string = m_edit.get(i).getText().toString();
}
And there is problem: result is always ""
What am i doing wrong?
My class source code
import android.app.Activity;
import android.widget.Toast;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.EditText;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import android.widget.ArrayAdapter;
import android.view.View.OnClickListener;
import android.view.*;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class AddCategory extends Activity {
private ArrayList<EditText> m_edit = null;
private EditAdapter m_adapter;
private EditText categoryName;
private MyDbAdapter dbAdapter;
private Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addcategory);
final Button categoryAddButton = (Button)findViewById(R.id.CategoryAddButton);
final Button fieldAddButton = (Button)findViewById(R.id.FieldAddButton);
final ListView fieldList = (ListView)findViewById(R.id.CategoryFieldList);
categoryName = (EditText)findViewById(R.id.CategoryNameEdit);
m_edit = new ArrayList<EditText>();
this.m_adapter = new EditAdapter (this, R.layout.categoryfieldlayout, m_edit);
fieldList.setAdapter(m_adapter);
dbAdapter = new MyDbAdapter(this);
context = getApplicationContext();
dbAdapter.open();
fieldAddButton.setOnClickListener(new OnClickListener()
{
public void onClick(View view){
EditText et = new EditText(AddCategory.this);
m_edit.add(et);
m_adapter.notifyDataSetChanged();
}
});
categoryAddButton.setOnClickListener(new OnClickListener()
{
public void onClick(View view){
int duration;
String error;
long categoryID;
;
int errCount = 0;
if (!categoryName.getText().toString().equals("")){
for (int i = 0;i<m_edit.size();i++){
if (m_edit.get(i).getText().toString().equals("")){
errCount++;
}
}
if (errCount != 0){
GroupItem group = new GroupItem(categoryName.getText().toString());
categoryID = dbAdapter.insertGroup(group);
for (int i = 0;i<m_edit.size();i++){
FieldItem field = new FieldItem(m_edit.get(i).getText().toString());
duration = Toast.LENGTH_SHORT;
error = m_edit.get(i).getText().toString();
Toast.makeText(context, error, duration).show();
}
}
else{
duration = Toast.LENGTH_SHORT;
error = "Field cannot be empty";
Toast.makeText(context, error, duration).show();
}
}
else{
duration = Toast.LENGTH_SHORT;
error = "Name cannot be empty";
Toast.makeText(context, error, duration).show();
}
}
});
}
private class EditAdapter extends ArrayAdapter<EditText>{
private ArrayList <EditText> items;
public EditAdapter(Context context, int textViewResourceId, ArrayList<EditText> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.categoryfieldlayout, null);
}
EditText et = (EditText)v.findViewById(R.id.fieldEdit);
return v;
}
}
}
When i update (write some text) EditText field of my custom listView item, i think, m_edit dont update its content automaticaly. So the problem is, how to force that update
ps. sorry for my poor english
From the code below, I guess you are going wrong by getting text from an ArrayList and not your EditText field.
m_edit = new ArrayList<EditText>();
for (int i = 0;i<m_edit.size();i++) {
_string = m_edit.get(i).getText().toString();
}
Simply set a ListView onClickListener and you will get the Edittext value for each listview item you click. In your case...
final ListView fieldList = (ListView)findViewById(R.id.CategoryFieldList);
fieldList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
EditText et = (EditText)v.findViewById(R.id.fieldEdit);
String myText = et.getText().toString();
Toast.makeText(getApplicationContext(), myText , Toast.LENGTH_SHORT).show();
}
});
can you provide you code snippets so get more idea what you are doing with edittext Arraylist.
From this i can see that you are adding edittext in arraylist and refreshing your listview. but did your listview refreshed with added edittext or not? Then that is the main problem with your code.
thanks for your source,
I think you are using listview and on button click you are trying to get edittext value. but how can you know that which position view is got selected from the listview.
I think there is some problem in what you are asking and what you doing. i think what you are doing is on single button click you try to get all edittext value.
You are getting blank value because in your listview you have not edited it..you can do it something like this.
Inside your adapter getview method put this code
public View getView(final int position, View convertView, ViewGroup parent) {
ed.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
list.get(position).edittext.setText(ed.getText().toString())
}
});
}
Hope this may help you.