When I run the following code the name of the Checkboxes are coming up as random strings (like android.widget.CheckBox#43e641b0.) Also I cannot click those added Checkboxes.
This is my java code:
package com.srk.android.rough1;
import java.util.ArrayList;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.app.ListActivity;
public class Rough1Activity extends ListActivity {
ArrayList<CheckBox> listItems=new ArrayList<CheckBox>();
ArrayAdapter<CheckBox> adapter;
private EditText taskNameEditText;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
adapter=new ArrayAdapter<CheckBox>(this, android.R.layout.simple_list_item_multiple_choice, listItems);
setListAdapter(adapter);
}
public void addItems(View v) {
taskNameEditText=(EditText)findViewById(R.id.TaskName);
String taskName=taskNameEditText.getText().toString();
CheckBox cb=new CheckBox(this);
cb.setText(taskName);
listItems.add(cb);
adapter.notifyDataSetChanged();
}
}
You are trying to display CheckBoxes as you would add an array of integers or Strings... I suggest a different approach:
public class Rough1Activity extends ListActivity {
private ArrayList<String> listItems = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private EditText taskNameEditText;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
// I like this layout, but it's your choice
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, listItems);
//adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, listItems);
setListAdapter(adapter);
// I guessed that you want a multiple choice list from your first layout choice. This is optional, you can remove it.
ListView listView = getListView();
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
// Here you only need to initialize taskNameEditText once
taskNameEditText = (EditText) findViewById(R.id.TaskName);
}
public void addItems(View v) {
// Add the current string in the EditText to the ListView
adapter.add(taskNameEditText.getText().toString());
}
}
You want to have a list of Strings and display the strings with a Checkbox. I changed your ArrayList and ArrayAdapter to String subtypes to reflex this and the layout android.R.layout.simple_list_item_checked adds the Checkbox features itself. Now the user will see the text they entered in a ListView with checkable rows.
Hope this helps!
Related
I have a activity, in which it has a button, on click of the button the app crashes problem is on line adapter.remove(list.get(i));
Logcat detail mention NullPointerException on the given line adapter.remove(list.get(i));
package com.example.veeresh.myphotogallery;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
public class MainActivity extends ListActivity {
/** Items entered by the user is stored in this ArrayList variable */
ArrayList list = new ArrayList();
/** Declaring an ArrayAdapter to set items to ListView */
ArrayAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Setting a custom layout for the list activity */
setContentView(R.layout.activity_main);
/** Reference to the add button of the layout main.xml */
Button btn = (Button) findViewById(R.id.btnAdd);
/** Reference to the delete button of the layout main.xml */
Button btnDel = (Button) findViewById(R.id.btnDel);
/** Defining the ArrayAdapter to set items to ListView */
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, list);
adapter.add("Item 1");
/** Defining a click event listener for the button "Add" */
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText) findViewById(R.id.txtItem);
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
/** Defining a click event listener for the button "Delete" */
OnClickListener listenerDel = new OnClickListener() {
#Override
public void onClick(View v) {
/** Getting the checked items from the listview */
SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
int itemCount = getListView().getCount();
for(int i=itemCount-1; i >= 0; i--)
{
if(checkedItemPositions.get(i)){
adapter.remove(list.get(i));
}
}
checkedItemPositions.clear();
adapter.notifyDataSetChanged();
}
};
/** Setting the event listener for the add button */
btn.setOnClickListener(listener);
/** Setting the event listener for the delete button */
btnDel.setOnClickListener(listenerDel);
/** Setting the adapter to the ListView */
setListAdapter(adapter);
}
}
Your adapter contains a list, and your MainActivity contains another list.
You are adding items to your Adapter, however this does not add items to the list in your Mainactivity. The list in your Adapter contains "Item 1", but the list in MainActivity does not.
OnClick you are trying to retrieve an item from the list in your MainActivity, which doesn't contain the item you are trying to retrieve, hence the NullpointerException
You should add or remove items from the list and then call adapter.notifyDataSetChanged();
Try:
//add an item
list.add("item 1");
adapter.notifyDataSetChanged();
//remove an item
list.remove(i);
adapter.notifyDataSetChanged();
I believe you should change your problematic line with this:
adapter.remove(list.getAdapter().getItem((checkedItemPositions.keyAt(i)));
I want to set Json values into a spinner list. The data I have:
JSONArray lang = jsonObject.getJSONArray("languages");
for (int i = 0; i < lang.length(); i++) {
String language = lang.getString(i);
}
How can i load String values into a spinner list?
ArrayAdapter<String> arrayAdapter = new ArrayAdapter(yourContext, android.R.layout.activity_list_item)
arrayAdapter.addAll(langList); // you need to add your lang.getString(i) to an array
yourSpinner.setAdapter(arrayAdapter);
and voila!
As i understand your problem, you have list of records and you want to show them in spinner in multiple activity.
For this you can create an Class that extends Application Class and create a list in that class.
once You receive response from you web api set data in list of application class.
Now where ever you want to display data in Spinner get it from Application class and render your spinner
See below Example -
public class MyApp extends Application{
private static ArrayList<String> mDataArrayList;
public static ArrayList<String> getmDataArrayList() {
return mDataArrayList;
}
public static void setmDataArrayList(ArrayList<String> mDataArrayList) {
MyApp.mDataArrayList = mDataArrayList;
}
#Override
public void onCreate() {
super.onCreate();
}
}
Call your web api and parse data as you code in your question -
ArrayList<String> mArrayList = new ArrayList<String>();
for (int i = 0; i < lang.length(); i++) {
String language = lang.getString(i);
mArrayList.add(language);
}
//Set Application class list
MyApp.setmDataArrayList(mArrayList);
Now when you want to display data in any class then get list by calling -
ArrayList<String> mArrayList = MyApp.getmDataArrayList();
//Code to display data in Spinner
Hope it will help you.
And dont forgot to add it to manifest of your application -
<application
android:allowBackup="true"
android:name=".MyApp"
....>
....
</application>
I'd suggest you to use Spinner class activity for future usages. Here is the example of spinner activity class (data receiver and displayer):
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class mySpinnerClass extends Activity implements
OnItemSelectedListener {
Spinner spinner;
int selectedValue;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner);
selectedValue = -1;
Intent i = getIntent();
dataSelector = i.getStringExtra("MessageText");
// Spinner element
spinner = (Spinner) findViewById(R.id.mySpinner);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Loading spinner data
loadSpinnerData();
}
private void loadSpinnerData() {
// Spinner Drop down elements
List<String> lables = yourData.get(dataSelector);
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
public void onItemSelected(AdapterView<?> parent, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
String label = parent.getItemAtPosition(position).toString();
//get the label and do anything you want with it
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
In caller activity:
Intent i = new Intent(getApplicationContext(), mySpinnerClass.class);
i.putExtra("MessageText",yourData);
startActivity(i);
If you want to send non-primitive data (in your example, this is a list) you need to use Serializable type while sending and receiving it. The following link illustrates this technique well:
http://javatechig.com/android/pass-a-data-from-one-activity-to-another-in-android
I have a spinner that show my array data list and delete button.
What I am trying to do is when I click on the delete button, it automatically deletes a selected spinner value, but I'm not certain how to do this.
In the delete button click function, deleted the selected spinner value after debugging my activity again but I want delete automatically a selected spinner value when I click on the delete button.
package quesansw.the1;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Dialog;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
public class View1 extends Activity {
SQLiteDatabase db;
ArrayAdapter adapter;
private String array_spinner[];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = openOrCreateDatabase("mydatabase.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
final Dialog d1 = new Dialog(this);
Window window = d1.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
//d1.setTitle("Login");
d1.setContentView(R.layout.view);
d1.show();
Button Click = (Button) d1.findViewById(R.id.Click);
Button Save = (Button) d1.findViewById(R.id.Save);
Button Delete = (Button) d1.findViewById(R.id.Delete);
ArrayList<String> list = new ArrayList<String>();
Cursor cursor = db.rawQuery("select * from records", null);
list.add("");
if (cursor.moveToFirst())
{
do
{
list.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
/*array_spinner=new String[20];
array_spinner[0]=list.get(0);*/
Spinner s = (Spinner) d1.findViewById(R.id.tittle_spinner);
adapter = new ArrayAdapter<Object>(this,android.R.layout.simple_spinner_item, list.toArray());
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
/*Save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Spinner s = (Spinner) d1.findViewById(R.id.tittle_spinner);
String str = s.getSelectedItem().toString();
System.out.println("********"+str);
Cursor cur1=db.rawQuery("select * from records where tittle='"+str+"' ",null);
cur1.moveToNext();
String str1=cur1.getString(1);
EditText ans = (EditText) d1.findViewById(R.id.text);
ans.setText(str1);
}
});*/
Delete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Spinner s = (Spinner) d1.findViewById(R.id.tittle_spinner);
String str = s.getSelectedItem().toString();
db.execSQL("delete from records where tittle='"+str+"' ");
}
});
Click.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Spinner s = (Spinner) d1.findViewById(R.id.tittle_spinner);
String str = s.getSelectedItem().toString();
System.out.println("********"+str);
Cursor cur1=db.rawQuery("select * from records where tittle='"+str+"' ",null);
cur1.moveToNext();
String str1=cur1.getString(1);
EditText ans = (EditText) d1.findViewById(R.id.text);
ans.setText(str1);
}
});
}
}
1) Here is my activity screen shot
2) Another screen shot with spinner values:
Why are you declaring and initializing your Spinner so many times? Just do it once
public class View1 extends Activity {
SQLiteDatabase db;
ArrayAdapter adapter;
private String array_spinner[];
Spinner spinner; // Declare your spinner here
then in onCreate()
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = openOrCreateDatabase("mydatabase.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
spinner = (Spinner) d1.findViewById(R.id.tittle_spinner); //initialize your spinner here
final Dialog d1 = new Dialog(this);
then when you click delete button call adapter.notifyDataSetChanged() to update your Array and spinner
In deleteButton's onClickListener, remove the selected spinner value from the array data list and call onnotifydatasetChanges or again setSpinner adapter with the new array list after deletion.
public class MainActivity extends Activity {
Spinner spin;
Button delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
delete = (Button) findViewById(R.id.button1);
spin = (Spinner) findViewById(R.id.spinner1);
final ArrayList<String> spinneritems = new ArrayList<String>();
spinneritems.add("item 1");
spinneritems.add("item 2");
spinneritems.add("item 3");
spinneritems.add("item 4");
spinneritems.add("item 5");
final ArrayAdapter<String> adp = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,spinneritems );
adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adp);
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String selectedSpinner = spin.getSelectedItem().toString();
spinneritems.remove(selectedSpinner);
adp.notifyDataSetChanged();
}
});
}
}
}
On delete button click listener add following code
Spinner s = (Spinner) d1.findViewById(R.id.tittle_spinner);
String str = s.getSelectedItem().toString();
adapter.remove(str);
adapter.notifyDataSetChanged();
s.setSelection(0);
I am able to extract the href elements from a page and store the results into a string array. Then display it inside a TextView. The problem comes if I try to display to a ListView. I don't know how to work with ArrayAdapters in this case. This is my working code that displays into a TextView.
package com.example.jsouptestarray;
import java.io.IOException;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.example.jsouptestarray.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.text.method.ScrollingMovementMethod;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView text;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyTask().execute();
}
private class MyTask extends AsyncTask<Void, Void, ArrayList<String>> {
ArrayList<String> arr_linkText=new ArrayList<String>();
#Override
protected ArrayList<String> doInBackground(Void... params) {
Document doc;
String linkText = "";
try {
doc = Jsoup.connect("https://www.google.com/").get();
Elements links = doc.getElementsByTag("a");
for (Element el : links) {
linkText = el.attr("href");
arr_linkText.add(linkText); // add value to ArrayList
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return arr_linkText; //<< retrun ArrayList from here
}
#Override
protected void onPostExecute(ArrayList<String> result) {
// get all value from result to display in TextView
for (String temp_result : result) {
System.out.println("links :: "+temp_result);
text = (TextView) findViewById (R.id.textView2);
text.append(temp_result + "\n" + "\n");
text.setMovementMethod(new ScrollingMovementMethod());
}
}
}
}
This is my attempt with the ListView, but I get an error and I don't understand how to fix it.
list = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, temp_result);
// Assign adapter to ListView
list.setAdapter(adapter);
Here is a screenshot of the error
I hope someone can help me fix it, and I appreciate your time!
Fourth element of the constructor is excess in your case. It can be used to set data at once, you should see API.
Try this:
list = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1,
android.R.id.text1);
for (String temp_result : result)
{
adapter.add(temp_result);
}
// Assign adapter to ListView
list.setAdapter(adapter);
Replace this with MainActivity.this. When you're inside the AsyncTask, this refers to the AsyncTask instance, which can't be passed to the constructor (different, unrelated, incompatible classes)
So you need to call an Activity as the argument and since your AsyncTask is part of an Activity, you can explictly reference the Activity instance with ClassName.this.
Something is wrong with my code. In the application, when I "add item", it doesn't show anything, and if I am clicking somewhere around the Android application, then "item" sometimes comes.
Can somebody help me?
package com.example.proov;
import java.util.ArrayList;
import com.example.proov.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class proovin extends Activity {
private ListView LView;
ArrayList <String>ar = new ArrayList<String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LView = (ListView) findViewById(R.id.ListView01);
// Set option as Multiple Choice. So that user can able to select more the one option
LView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, ar));
LView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button b = (Button) findViewById(R.id.add_item);
final EditText d = (EditText) findViewById(R.id.title);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ar.add(d.getText().toString());
}
});
}
}
Use below code instead of your code.
public class proovin extends Activity {
private ListView LView;
ArrayList <String>ar = new ArrayList<String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LView = (ListView) findViewById(R.id.ListView01);
// Set option as Multiple Choice. So that user can able to select more
// the one option
final ArrayAdapter<String> adpt=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, ar);
LView.setAdapter(adpt);
LView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button b = (Button) findViewById(R.id.add_item);
final EditText d = (EditText) findViewById(R.id.title);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ar.add(d.getText().toString());
adpt.setNotifyOnChange(true);
LView.setAdapter(adpt);
}
});
}
}
The item is likely getting added to the ArrayList, but that is different from getting added to the ListView. You need to tell the ListView that you updated the data model so that it knows to look. See ArrayAdapter.notifyDatasetChanged()
you can use this add string to list on a button click
final String a[]={"hello","world"};
final ArrayAdapter<String> at=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a);
final ListView sp=(ListView)findViewById(R.id.listView1);
sp.setAdapter(at);
final EditText et=(EditText)findViewById(R.id.editText1);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
int k=sp.getCount();
String a1[]=new String[k+1];
for(int i=0;i<k;i++)
a1[i]=sp.getItemAtPosition(i).toString();
a1[k]=et.getText().toString();
ArrayAdapter<String> ats=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a1);
sp.setAdapter(ats);
}
});