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
Related
I've looked up similar post regarding this question but they didn't solve my issue, so here it is.
I'm trying to set a setOnItemClickListener, for when I click on any item of my list I will open a dialog with the info (retrieve from the list) on the clicked list and more info. But i'm struggling to implement the setOnItemClickListener part.
I'm getting and error in line: myList.setOnItemClickListener(new OnItemClickListener()){
package com.example.proyectoprueba;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;;
public class PlantillaChina extends ActionBarActivity{
// DB Class to perform DB related operations
DBController controller = new DBController(this);
// Progress Dialog Object
ProgressDialog prgDialog;
HashMap<String, String> queryValues;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.lista);
Intent myIntent = getIntent();
String value = myIntent.getStringExtra("key");
TextView titulo=(TextView)findViewById(R.id.titulo);
// Get Platos records from SQLite DB
ArrayList<HashMap<String, String>> platoList = controller.getAllEntremeses();
if (value.equals("entremeses")){
platoList = controller.getAllEntremeses();
titulo.setText(value);
}else if(value.equals("arroces y pasta")){
platoList = controller.getAllArrocesyPasta();
titulo.setText(value);
}else if(value.equals("mar")){
platoList = controller.getAllMar();
titulo.setText(value);
}else if(value.equals("carnes")){
platoList = controller.getAllCarnes();
titulo.setText(value);
}
// If Platos exists in SQLite DB
if (platoList.size() != 0) {
// Set the Plato Array list in ListView
ListAdapter adapter = new SimpleAdapter(PlantillaChina.this, platoList, R.layout.itemlista, new String[] {
"platoId", "platoNombre", "platoDescripcion", "platoPrecio" }, new int[] {R.id.codigo, R.id.nombre, R.id.descripcion, R.id.precio });
ListView myList = (ListView) findViewById(R.id.listaplatos);
myList.setAdapter(adapter);
myList.setOnItemClickListener(new OnItemClickListener()){
}
}
Thank you for your time
It think you want something like this.
myList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id)
{
// You have the position available here as well as the clicked view.
}
});
You need to actual define the OntItemClickListener to do something.
First, the code you have doesn't make much sense. You want something like this:
myList.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
// Your code here
}
});
Basically you are creating your own OnItemClickListener class, and overriding the OnItemClick method. This callback will get called whenever an item in your list is clicked. You can do whatever processing you would like inside that function.
i have a list of object in an activity in which a button in the same activity adds an object to it on every click
i want to be capable to access that list and iterate it from any other activity
i made it public but it gave me an error !
package com.fawzyx.movie_rental_store;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MovieReg_activity extends Activity {
public List<movie> movies = new ArrayList<movie>();
String movName ;
int dvdNo ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mov_reg_layout);
EditText etmovie_name = (EditText)findViewById(R.id.etmovname);
EditText etdvd_no = (EditText)findViewById(R.id.etdvds);
Button btMovie_submit = (Button)findViewById(R.id.btmovsubmit);
movName= etmovie_name.getText().toString();
dvdNo = Integer.parseInt(etdvd_no.getText().toString()); // to string then to int :)
btMovie_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
movies.add(new movie(movName , dvdNo) );
Toast.makeText(MovieReg_activity.this, "Movie Added", Toast.LENGTH_LONG).show();
}
});
}
}
is there a way to access and iterate the list movies from any other activity ?
You can use a static way to access to this list :
public static List<movie> movies = new ArrayList<movie>();
Then from the other activity :
int size = MovieReg_activity.movies.size(); // exp: check the size
for(movie m : MovieReg_activity.movies){
// do something with m
}
if you want to make a global list, create a static variable or put it in your application class and access it via context.
Search about creating a custom application class.
Maybe use a singleton class that holds your movie list.
Then you'll be able to access it everywhere.
http://androidresearch.wordpress.com/2012/03/22/defining-global-variables-in-android/
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.
I am very new to this API.I have knowledge on doing samples with this API.after that my requirement is display the Column graph based on Spinner Values selection .the query table data is coming correctly the problem is not appending the latest values to the chart .
In My App i have one spinner name it as Customer Name:
when i change the spinner-value i am sending the Customer name to input parameter to sqllite and display the graph for that i write the following code.
package com.appulento.salestracking;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Vector;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import com.appulento.salestrackingdb.DBAdapter;
import com.artfulbits.aiCharts.ChartView;
import com.artfulbits.aiCharts.Base.ChartArea;
import com.artfulbits.aiCharts.Base.ChartAxis;
import com.artfulbits.aiCharts.Base.ChartCollection;
import com.artfulbits.aiCharts.Base.ChartCollection.IChangeListener;
import com.artfulbits.aiCharts.Base.ChartNamedCollection;
import com.artfulbits.aiCharts.Base.ChartPalette;
import com.artfulbits.aiCharts.Base.ChartPoint;
import com.artfulbits.aiCharts.Base.ChartSeries;
import com.artfulbits.aiCharts.Types.ChartTypes;
public class SalesTrackingByCustomer extends Activity {
private DBAdapter db;
private Spinner spinner1, spinner2;
private String[] prodctnames;
private String[] prodctnames1;
private double[] product_1;
private double[] product_2;
public int count;
public String custid;
public Sample customerdetails;
public ChartCollection<String> collection;
ChartArea area;
ChartArea area1;
private SimpleAdapter mSchedule;
Vector<String> vec_custid=new Vector<String>();
Vector<String> vec_oldno=new Vector<String>();
Vector<String> vec_productid=new Vector<String>();
Vector<String> vec_qty=new Vector<String>();
private ListView mListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bycustomers);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
mListView=(ListView)findViewById(R.id.listView1);
prodctnames=new String[10];
product_1=new double[10];
prodctnames1=new String[10];
product_2=new double[10];
db=new DBAdapter(this);
final ChartView chartView = (ChartView) findViewById(R.id.chartView);
ChartPalette palette = new ChartPalette(0xffffd7e8);
chartView.setPalette(palette);
final ChartSeries product1 = new ChartSeries("P1", ChartTypes.Column);
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
int position=spinner1.getSelectedItemPosition();
System.out.println("=====ITEM POSITION======"+position);
final String selected=arg0.getItemAtPosition(arg2).toString();
System.out.println("=====IN SELECTED======"+selected);
//finish();
db.open();
Cursor customer=db.fetchorderCustomername(selected);
custid=customer.getString(0);
System.out.println("=====CUSTOMER NAME ID======"+custid);
Cursor cursor=db.fetchorderDetails(custid);
count=cursor.getCount();
System.out.println("=====COUNT======"+count);
int i=0;
while (i<count)
{
String productid=cursor.getString(1);
prodctnames[i]=productid;
String qty=cursor.getString(2);
product_1[i]=Double.parseDouble(qty);
System.out.println("=====PROID======"+prodctnames[i]+"=====QUANTITY======"+product_1[i]);
cursor.moveToNext();
i++;
}
for (int j = 0; j < count; j++)
{
ChartPoint point = product1.getPoints().addXY(j, product_1[j]);
point.setAxisLabel(prodctnames[j]);
}
if(position==0)
{
chartView.refreshDrawableState();
chartView.getSeries().add(product1);
area = chartView.getAreas().get(0);
area.getDefaultXAxis().setLabelsMode(ChartAxis.LabelsMode.SeriesLabels);
}
if(position==1)
{
chartView.refreshDrawableState();
chartView.getSeries().add(product1);
area1 = chartView.getAreas().get(0);
area1.getDefaultXAxis().setLabelsMode(ChartAxis.LabelsMode.SeriesLabels);
}
//area.refresh();
db.close();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
My problem is at first time Application Launch the graph is Displaying successfully when i change the Spinner value selection the app got closed and display the fallowing exception in my log cat:
java.security.InvalidParameterException: This name already presents at com.artfulbits.aiCharts.Base.ChartNamedCollection.validateName(SourceFile:128 ) at com.artfulbits.aiCharts.Base.ChartNamedCollection.validate
please see once and let me know where i am doing Mistake in my code.The dynamic vlaues is not appending to that chart in the above code.
Thanks in Advance....
The problem is that you're trying to add new area with the same name. I'm not exactly well versed in the API enough, but i'd imagine that the issue comes when you try this line a second time:
chartView.getSeries().add(product1);
I also noticed that you never used the following:
prodctnames1=new String[10];
product_2=new double[10];
If i could make a suggestion, perhaps it isn't best to have all your code in a click listener. maybe you can fill your datasets at the beginning and then only show the graphs upon using the spinner. Because if one clicks the spinner more than once, you have to go to the database to get the same information.
I have an array that successfully shows as a listview as the main activity. I've been using many tutorials in the past few days to try to find out the best way to start different activities from items clicked on this listview. I've seen everything from switch statements to calling a class by a variable, but nothing seems to work. I would possibly use an if statement but my list is over 120 entries. Any suggestions?
Why don't you put the class as a parameter of the item ?
package com.ybi;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class YbiListActivity extends ListActivity
{
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
ClickableItem[] values = new ClickableItem[1];
// here you can add your label and your activity
values[0] = new ClickableItem("Hello", YbiListActivity.class);
ArrayAdapter<ClickableItem> adapter = new ArrayAdapter<ClickableItem>(this, android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
ClickableItem item = (ClickableItem) getListAdapter().getItem(position);
Intent intent = new Intent(YbiListActivity.this, (Class<?>) item.itemClass);
startActivity(intent);
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
}
private class ClickableItem
{
public String itemLabel;
public Object itemClass;
public ClickableItem(String ilabel, Object iclass)
{
itemLabel = ilabel;
itemClass = iclass;
}
#Override
public String toString()
{
return itemLabel;
}
}
}
You could create two new arrays in arrays.xml (list_items and list_item_activities)
Then, when an item is selected, you can use its index to find the associated activity.
<string-array name="list_items">
<item>ExampleActivity</item>
...
</string-array>
<string-array name="list_item_activities">
<item>com.example.app.ExampleActivity</item>
...
</string-array>
To explain a bit more, you would use the list_items to create the list:
String[] list = getResources().getStringArray("list_items");
for(int i = 0; i < list.length; i++){
// add the item
}
Then when the item is clicked:
public void onListItemClick(ListView l, View v, int position, long id){
String[] activities = getResources().getStringArray("list_item_activities");
// activities[position] is what you would use
}