Android: Can't seemed to assign variable with new value - android

I am having trouble with the variable: URL_STRING. I can't seem to add a value from another variable to URL_String. It just null for some reason. Your assistance would be appreciated.
public class HomeScreen extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
ListView listView;
Spinner spinner;
EditText search;
Button bt;
String URL_STRING;
String entity;
String term;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
listView = (ListView) findViewById(R.id.listView);
spinner = (Spinner) findViewById(R.id.spinner);
search = (EditText) findViewById(R.id.search);
term = search.getText().toString();
bt = (Button) findViewById(R.id.searchBtn);
ArrayAdapter<CharSequence> entityAdapter = ArrayAdapter
.createFromResource(this, R.array.Entities,
android.R.layout.simple_spinner_item);
spinner.setAdapter(entityAdapter);
spinner.setOnItemSelectedListener(this);
}
This is where I am having trouble. URL_STRING is still null
public void addURL(View view) {
if(entity == "Select" && term != null){
URL_STRING = String.format(getResources().getString(R.string.url1),term);
SearchDownloader searchDownloader = new SearchDownloader(this);
searchDownloader.execute();
listView.setVisibility(View.VISIBLE);
}else if(term == null){
Toast.makeText(getApplicationContext(), "Please enter a search term",
Toast.LENGTH_LONG).show();
}else{
URL_STRING = String.format(getResources().getString(R.string.url2), term, entity);
SearchDownloader searchDownloader = new SearchDownloader(this);
searchDownloader.execute();
listView.setVisibility(View.VISIBLE);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
entity = String.valueOf(spinner.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
entity = null;
}
}

I am not very sure about the adapter and the array being assigned to it.
I have created something which are looking for, Kindly try this, code is available on Github as well have a look at it if i may have missed something. to load the imgae I am using a library called picasso which you can easily import by adding following code to the dependencies block in the build.gradle file like this
compile 'com.squareup.picasso:picasso:2.5.2'
and you would be able to use picasso
public class SpinnerTestTwoActivity extends Activity {
private Spinner url_Spinner;
private Button load_image_Button;
private ImageView url_image_ImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_test_two);
initializeUI();
}
private void initializeUI() {
url_Spinner = (Spinner) findViewById(R.id.SpinnerTestTwoActivity_url_spinner);
load_image_Button = (Button) findViewById(R.id.SpinnerTestTwoActivity_load_image_button);
url_image_ImageView = (ImageView) findViewById(R.id.SpinnerTestTwoActivity_image_from_url_imageView);
String[] url_array = getResources().getStringArray(R.array.url_images);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.simple_spinner_dropdown_item, url_array);
url_Spinner.setAdapter(adapter);
url_Spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String image_url = (String)url_Spinner.getItemAtPosition(position);
Picasso.with(getApplicationContext()).load(image_url).into(url_image_ImageView);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
activity_spinner_test_two.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:gravity="center"
android:orientation="vertical">
<Spinner
android:id="#+id/SpinnerTestTwoActivity_url_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp" />
<Button
android:id="#+id/SpinnerTestTwoActivity_load_image_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:text="Load Image"
android:textAllCaps="false" />
<ImageView
android:id="#+id/SpinnerTestTwoActivity_image_from_url_imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="4dp"
android:layout_weight="1"
android:scaleType="fitCenter" />
</LinearLayout>
url_images
This is the array which you will make in the arrays.xml file which is in the res/values directory
<array name="url_images">
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7emgtQk5rdEE3bW8/style_icons_system_intro_principles_simple.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7MGhHV055eGk0R2M/style_icons_system_intro_principles_intuitive.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7MG80dmpHT0RidGs/style_icons_system_intro_principles_actionable.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7blViQzF0azNqZU0/style_icons_system_intro_principles_consistent.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7VXlvR05VSWhPZTg/style_icons_system_grid_geometry2.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7SUV1b2Z3b3NBazA/style_icons_system_best_do1.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7azQ4WThPb25NOGc/style_icons_system_best_do3.png</item>
</array>
Output

Related

Spinner doesn't display data after being clicked

So I have been trying to display a list of data from my local mysql server using API calls like getAll,getByID,etc. on the spinner in a drop down style. However when I click on the spinner nothing happens. Here's my code for the passing the data to the spinner:-
public class markAbsentee extends AppCompatActivity implements OnItemSelectedListener{
Button fromDate, toDate, save;
TextView displayFDate, displayTDate;
Spinner genieS;
List genieList;
private Spinner getGenieS;
private List<Genie> getGenieList;
private Button getFromDate;
private Button getToDate;
private Button getSave;
private TextView getDisplayFDate;
private TextView getDisplayTDate;
private DatePickerDialog.OnDateSetListener mDateSetListener, mDateSetListener1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mark_absentee);
getGenieS = (Spinner) findViewById(R.id.geniespinner);
getFromDate = (Button) findViewById(R.id.button2);
getToDate = (Button) findViewById(R.id.button3);
getDisplayFDate = (TextView) findViewById(R.id.fromDate);
getDisplayTDate = (TextView) findViewById(R.id.toDate);
new SpinTask().execute();
//I have called the AsyncTask here which contains the get() API
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Genie selected = (Genie)parent.getSelectedItem();
Toast.makeText(markAbsentee.this, selected.id + " " + selected.name, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
class SpinTask extends AsyncTask<Void, Void, List<Genie>>{
private Exception exception;
protected void onPreExecute(){}
#Override
protected List<Genie> doInBackground(Void... voids) {
GenieService genieService = new GenieService();
return genieService.getAll();
}
protected void onPostexecute(List<Genie> genies){
if(genies == null){
new ArrayList<Genie>();
}else {
List<String> rows = genies.stream().map(genie -> getRow(genie)).collect(Collectors.toList());
ArrayAdapter<Genie> adapter = new ArrayAdapter<Genie>(markAbsentee.this, android.R.layout.simple_spinner_item, genies);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Toast.makeText(markAbsentee.this, "Clicked", Toast.LENGTH_LONG).show();
genieS.setAdapter(adapter);
}
}
private String getRow(Genie g){
return String.format("%s %s", g.name, g.salary);
}
}
}
Here's the layout of the spinner:-
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bcak"
android:orientation="vertical"
tools:context="com.codionics.geniem.markAbsentee">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="76dp"
android:layout_marginTop="59dp"
android:text="Enter Absentee"
android:textSize="30dp"
android:textColor="#ffff" />
<Spinner
android:id="#+id/geniespinner"
android:layout_width="350dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/textView4"
android:layout_marginStart="20dp"
android:layout_marginTop="27dp"
android:popupBackground="#color/colorPrimary"
android:spinnerMode="dropdown"
android:autofillHints="Select genie" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
P.S:- GenieService is the service class for calling the API's. I want to display the name and salary of the person in the spinner drop down list.Thanks in advance for the help.
when you set spinner value it containg only single value like string,integer etc show. when you getting data then it add data into list like below ...
listArray.addAll("Your Value");
then after define array adapter like below and set spinner ..
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,strings);
spinner.setAdapter(arrayAdapter);
then after you called any function on spinner item selection used like below code ...
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(),"Hello",0).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});

Remove a few values from ListView built with BaseAdapter

I am writing the basic task management application. I am using base adapter to work with ListView. I wonder how I can remove (a few) checked values from the list? And how I can remove only one value with long click?
if this posible with my adapter? I tried a few options but nothing worked.
Here is my code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="#+id/btn1"
android:layout_width="50dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:text="\u2713"
android:background="#drawable/add_btn"
android:onClick="knopka2"/>
<EditText
android:id="#+id/input"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#id/btn1"
android:hint="put your task here"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:divider="#drawable/deriver"
android:layout_below="#+id/input"
android:layout_centerHorizontal="true"
android:choiceMode="multipleChoice" />
<TextView
android:id="#+id/ttl"
android:layout_below="#id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/tryClear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/ttl"
android:onClick="tryClear"
/>
</RelativeLayout>
This is my Activity:
public class Trird extends AppCompatActivity {
Button btn;
EditText input4;
TextView ttl;
ListView list;
public static ArrayList<String> taskList = new ArrayList<String>();
SparseBooleanArray sparseBooleanArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third);
input4 = (EditText) findViewById(R.id.input);
btn = (Button) findViewById(R.id.btn1);
list = (ListView) findViewById(R.id.listView);
ttl = (TextView)findViewById(R.id.ttl);
}
public String[] putToArray() {
String ag = input4.getText().toString().trim();
if (ag.length() != 0) {
taskList.add(ag);
input4.setText("");
}
String[] abc = taskList.toArray(new String[taskList.size()]);
return abc;
}
public void knopka2(View v) {
final String[] ListViewItems = putToArray(); //
list = (ListView) findViewById(R.id.listView);
list.setAdapter(new MyAdapter(ListViewItems, this));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View tv, int i, long id) {
///tv.setBackgroundColor(Color.YELLOW);
///ttl.setText("selected: " + list.getAdapter().getItem(i));
sparseBooleanArray = list.getCheckedItemPositions();
String ValueHolder = "";
int a = 0;
while (a < sparseBooleanArray.size()) {
if (sparseBooleanArray.valueAt(a)) {
ValueHolder += ListViewItems[sparseBooleanArray.keyAt(a)] + ",";
}
a++;
}
ValueHolder = ValueHolder.replaceAll("(,)*$", "");
Toast.makeText(Trird.this, "ListView Selected Values = " + ValueHolder, Toast.LENGTH_LONG).show();
if(ValueHolder!=null){
taskList.remove(ValueHolder);
}
}
});
}
}
This is my adapter:
public class MyAdapter extends BaseAdapter {
private final Context context;//Context for view creation
private final String[] data;//raw data
public MyAdapter(String[] data, Context context){
this.data=data;
this.context=context;
}
//how many views to create
public int getCount() {
return data.length;
}
//item by index (position)
public Object getItem(int i) {
return data[i];
}
//ID => index of given item
public long getItemId(int i) {
return i;
}
//called .getCount() times - for each View of item in data
public View getView(int i, View recycleView, ViewGroup parent) {
if(recycleView==null)recycleView = LayoutInflater.from(context).inflate(R.layout.item,null);
((TextView)recycleView).setText(data[i]);//show relevant text in reused view
return recycleView;
}
}
And this is how looks like item in ListView.
<CheckedTextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:drawableRight="?android:attr/listChoiceIndicatorMultiple"
/>
The problem is that you are trying removing item using the ListView remove methode.
Just remove the selected item from the list using the remove() method of your Adapter.
A possible way to do that would be:
CheckedTextView checkedText= baseAdapter.getItem([POSITION OF THE SELECTED ITEM]);
baseAdapter.remove(checkedText);
baseAdapter.notifyDataSetChanged();
put this code inside the wanted button click and there you go.

ListView not showing text on items

I want to display text input from an editText and show it in a listView using an ArrayAdapter, when clicking a button, the listView does gets an item added but without the text :
here is the code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.blink.blink.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="61dp">
<EditText
android:layout_width="280dp"
android:layout_height="60dp"
android:hint="Type a quote .. "
android:id="#+id/quoteField" />
<Button
android:layout_width="wrap_content"
android:layout_height="60dp"
android:text="Add Quote"
android:id="#+id/addQuote"
android:fontFamily="sans-serif-condensed"
android:background="#f6546a"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#id/quoteField" />
</RelativeLayout>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/quotelistView"
android:foreground="#f6546a"/>
</LinearLayout>
and :
public class MainActivity extends AppCompatActivity {
Button createBtn ;
EditText quoteField;
ListView quotesListView;
ArrayList<String> quotesArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createBtn = (Button) findViewById(R.id.addQuote);
quoteField = (EditText) findViewById(R.id.quoteField);
quotesListView = (ListView) findViewById(R.id.quotelistView);
quotesArrayList = new ArrayList<>();
createBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
quotesArrayList.add(quoteField.getText().toString());
SetAdapter();
quoteField.setText(" ");
}
});
}
private void SetAdapter()
{
ArrayAdapter<String> Adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, quotesArrayList);
quotesListView.setAdapter(Adapter);
}
}
You do not need to reset the adapter everytime you change the data in the array. What you should do is keep a reference to the adapter and call adapter.notifyDataSetChanged() when you change the data in the list
public class MainActivity extends AppCompatActivity {
Button createBtn ;
EditText quoteField;
ListView quotesListView;
ArrayList<String> quotesArrayList;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createBtn = (Button) findViewById(R.id.addQuote);
quoteField = (EditText) findViewById(R.id.quoteField);
quotesListView = (ListView) findViewById(R.id.quotelistView);
quotesArrayList = new ArrayList<>();
adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, quotesArrayList);
quotesListView.setAdapter(adapter);
createBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
quotesArrayList.add(quoteField.getText().toString());
adapter.notifyDataSetChanged();
quoteField.setText(" ");
}
});
}
}
Try it!
createBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
quotesArrayList.add(quoteField.getText().toString());
SetAdapter(quotesArrayList);
quoteField.setText(" ");
}
});
}
private void SetAdapter(ArrayList<String> quotesArrayList)
{
ArrayAdapter<String> Adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, quotesArrayList);
quotesListView.setAdapter(Adapter);
Adapter.notifyDataSetChanged();
}

How do calculate multiple spinner value with edit text?

Im new in android programing, I want make calculating with multiple spinner that have value string and edit text. and proccess with button click and show on text view. please healp me to fix so i can learn next subject.
THx
My activity .java code:
public class MainActivity extends Activity {
private EditText jumlah;
String[] spinnerValues = { "Bakso", "Es Buah" };
String[] spinnerSubs = {"10000", "8000" };
int total_images[] = { R.drawable.bakso, R.drawable.es_buah };
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner mySpinner = (Spinner) findViewById(R.id.spinner_show);
mySpinner.setAdapter(new MyAdapter(this, R.layout.menu_resto,
spinnerValues));
jumlah = (EditText) findViewById(R.id.editText1);
button1 = (Button) findViewById(R.id.button1);
initButton();
}
private void initButton() {
button1.setOnClickListener(new OnClickListener() {
// this one performs an action when our button is clicked. it performs whatever is below
#Override
public void onClick(View v) {
// String strA = i want call the spinersubs value that chsoed. how ?
String strB = jumlah.getText().toString();
Double dblAnswer = doCalc(strA, strB);
TextView lblAnswer = (TextView) findViewById(R.id.lblAnswer);
// the disadvantage is that we can't do anything to it outside of this curly
// in general it's wasteful to use fields when you can suffice with local variable
String answer = String.valueOf(dblAnswer);
// we get our answer and turn it to a string.
lblAnswer.setText(answer);
// finally we set our result to the textView.
}
});
}
public double doCalc(String a, String b) {
double dblA = Double.parseDouble(a);
double dblB = Double.parseDouble(b);
return dblA * dblB;
}
class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context ctx, int txtViewResourceId, String[] objects) {
super(ctx, txtViewResourceId, objects);
}
#Override
public View getDropDownView(int position, View cnvtView, ViewGroup prnt) {
return getCustomView(position, cnvtView, prnt);
}
#Override
public View getView(int pos, View cnvtView, ViewGroup prnt) {
return getCustomView(pos, cnvtView, prnt);
}
public View getCustomView(int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View mySpinner = inflater.inflate(R.layout.menu_resto, parent,
false);
TextView main_text = (TextView) mySpinner
.findViewById(R.id.text_main_seen);
main_text.setText(spinnerValues[position]);
TextView subSpinner = (TextView) mySpinner
.findViewById(R.id.sub_text_seen);
subSpinner.setText(spinnerSubs[position]);
ImageView left_icon = (ImageView) mySpinner
.findViewById(R.id.left_pic);
left_icon.setImageResource(total_images[position]);
return mySpinner;
}
Here my XML
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="X - Resto Menu"
android:textSize="30px" />
<Spinner
android:id="#+id/spinner_show"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100px"
android:drawSelectorOnTop="true" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner_show"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:ems="10" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner_show"
android:layout_centerHorizontal="true"
android:layout_marginTop="23dp"
android:text="Jumlah Pesanan" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:onClick="#string/hitung"
android:text="#string/pesan" />
<TextView
android:id="#+id/lblAnswer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:text="" />
You need to implement CustomOnItemSelectedListener for Spinner like
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
and then set this Listener to your Spinner like
mySpinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
and in Button click you'll get a Spinner selected value like
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MyAndroidAppActivity.this,
"OnClickListener : " +
"\nSpinner : "+ String.valueOf(mySpinner.getSelectedItem())
,Toast.LENGTH_SHORT).show();
}
});
Go to this for Tutorial

ListActivity Android

Does somebody know why ListActivity won't work and when I change it to Activity base class, with slight changes it works, but onClick() method still doesn't. I'm trying only to put some strings into the list... Here's the code:
public class TestDataBaseActivity extends Activity implements OnClickListener {
private CommentsDataSource datasource;
ListView m_list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datasource = new CommentsDataSource(this);
datasource.open();
List<Comment> values = datasource.getAllComments();
m_list = (ListView) findViewById(R.id.listView1);
// Use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
android.R.layout.simple_list_item_1, values);
m_list.setAdapter(adapter);
Button add = (Button)findViewById(R.id.button_add);
Button delete = (Button)findViewById(R.id.button_delete);
add.setOnClickListener(this);
delete.setOnClickListener(this);
}
// Will be called via the onClick attribute
// of the buttons in main.xml
#Override
public void onClick(View view) {
#SuppressWarnings("unchecked")
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) m_list.getAdapter();
Comment comment = null;
switch (view.getId()) {
case R.id.button_add:
String[] comments = new String[] {
"Cool", "Very nice", "Hate it"
};
int nextInt = new Random().nextInt(3);
// Save the new comment to the database
comment = datasource.createComment(comments[nextInt]);
adapter.add(comment);
break;
case R.id.button_delete:
if (m_list.getAdapter().getCount() > 0) {
comment = (Comment) m_list.getAdapter().getItem(0);
datasource.deleteComment(comment);
adapter.remove(comment);
}
break;
}
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
Here is XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TestDataBaseActivity" >
<Button
android:id="#+id/button_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add_new" />
<Button
android:id="#+id/button_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/button_add"
android:text="#string/delete_first" />
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/button_add"
android:padding="15dp" >
</ListView>
</RelativeLayout>
I edited now to extend Activity, now "only" onClick() dont work...
Thanks in advance!
For a ListActivity, you should override onListItemClick() instead:
#Override
protected void onListItemClick(ListView lv, View v, int position, long id){
}
Since you are extending ListActivity you need to have an Listview with android:id="#android:id/list".
if you want to use #+id/lst_id then dont extend ListActivity, just extended Activity.
And whenever you are using Listview you need to implement OnItemClickListener not OnClickListener.
and override the default OnItemClick method
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
you should implement OnClickListener
public class TestDatabaseActivity extends ListActivity implements
OnClickListener{
try following code a simple list activity
public class MainActivity extends ListActivity implements OnItemClickListener {
ListView listView;
static final String[] SPORTS = {"Shuttle Badminton", "Tennis", "FootBall",
"Basket Ball","Table Tennis", "Chess","Hockey"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listView = getListView();
//setting adapter
listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(),R.layout.list_item,SPORTS));
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
TextView tv = (TextView)view.findViewById(R.id.text1);
Toast.makeText(getApplicationContext(),"Position is: "+position,Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"Text is: "+tv.getText().toString(),Toast.LENGTH_SHORT).show();
}
}
here list_item is an xml having following code
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="#android:color/black"
android:padding="10dp" />
Use this code for list activity and modify row xml according to your needs.
hope this helps..
This is what's troubling you:
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) m_list.getAdapter();
Build a global object for your adapter instead. ( Declare it before onCreate() )

Categories

Resources