How to synchronize android spinner of two different activity - android

I have two activity.Both activity loaded the same data in the spinner from server.and both activity populate properly.I'm not getting proper idea that change in one spinner item position also display the same spinner's item when switch to other activity.How to synchronize both spinners of two different activities.
private class BackTask extends AsyncTask<Void,Void,Void> {
ArrayList<String> list;
protected void onPreExecute(){
super.onPreExecute();
list=new ArrayList<>();
}
protected Void doInBackground(Void...params){
InputStream is=null;
String result="";
try{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost= new HttpPost("http://my_url/Service.asmx/GetServiceList");
HttpResponse response=httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
}catch(IOException e){
e.printStackTrace();
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
result+=line;
}
is.close();
//result=sb.toString();
}catch(Exception e){
e.printStackTrace();
}
// parse json data
try{
JSONArray jArray =new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject jsonObject=jArray.getJSONObject(i);
// add interviewee name to arraylist
list.add(jsonObject.getString("ServiceName"));
}
}
catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result){
listItems.addAll(list);
adapter.notifyDataSetChanged();
}
}

public class StaticResources
{
private List<String> sDataSource = new ArrayList<String>();
public List<String> getDataSource() {...}
public void setDataSource(..) {...}
}
In both activities, refer to StaicResources.getDataSource(), that is it.

Try with this way
public static ArrayList listid,listdata;
onPostExecute(){
try{
JSONArray jarrvideos=new JSONArray(responcedata);
for(int i=0;i<jarrvideos.length();i++){
JSONObject jobj = jarrvideos.getJSONObject(i);
listid.add(jobj.getString("id"));
listdata.add(jobj.getString("id"));
}
BindSpinnerData();
}catch(Exception e){
e.printStackTrace();
}
}
private void BindSpinnerData() {
ArrayAdapter<String> spinnerLocation = new
ArrayAdapter<String(MedicalSurgical.this, R.layout.spinneritem, listdata);
spinnerLocation.setDropDownViewResource(R.layout.spinnerpopupblack);
spnDatasecond.setAdapter(spinnerLocation);
}
now it will display your first activity dpinner data if you need another activity same spinner data then you need to access listid,listdata array list in another class
for Accessing classname.listid or classname.listdata

Related

How we can create multiple spinners with MySQL database value in Android?

I am working with a project with multiple spinners in a single app, which fetches data from a MySQL database and shown in spinners. In this code, only one spinner is used, it collect data from MySQL database, how we can use more than one spinner in this.
public class MainActivity extends ActionBarActivity {
ArrayList<String> listItems=new ArrayList<>();
ArrayAdapter<String> adapter;
Spinner sp,sp1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp=(Spinner)findViewById(R.id.spinner);
adapter=new ArrayAdapter<String>(this,R.layout.spinner_layout,R.id.txt,listItems);
sp.setAdapter(adapter);
}
public void onStart(){
super.onStart();
BackTask bt=new BackTask();
bt.execute();
}
private class BackTask extends AsyncTask<Void,Void,Void> {
ArrayList<String> list;
protected void onPreExecute(){
super.onPreExecute();
list=new ArrayList<>();
}
protected Void doInBackground(Void...params){
InputStream is=null;
String result="";
try{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost= new HttpPost("http://192.168.1.2/agriculture.php");
HttpResponse response=httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
}catch(IOException e){
e.printStackTrace();
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
result+=line;
}
is.close();
//result=sb.toString();
}catch(Exception e){
e.printStackTrace();
}
try{
JSONObject jsono = new JSONObject(result);
JSONArray jArray = jsono.getJSONArray("actors");
for(int i=0;i<jArray.length();i++){
JSONObject jsonObject=jArray.getJSONObject(i);
list.add(jsonObject.getString("name"));
}
}
catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result){
listItems.addAll(list);
adapter.notifyDataSetChanged();
}
}
public class MainActivity extends ActionBarActivity {
ArrayList<String> listItems=new ArrayList<>();
ArrayAdapter<String> adapter;
Spinner sp,sp1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp=(Spinner)findViewById(R.id.spinner);
}
public void onStart(){
super.onStart();
BackTask bt=new BackTask();
bt.execute();
}
private class BackTask extends AsyncTask<Void,Void,Void> {
ArrayList<String> list;
protected void onPreExecute(){
super.onPreExecute();
list=new ArrayList<>();
}
protected Void doInBackground(Void...params){
InputStream is=null;
String result="";
try{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost= new HttpPost("http://192.168.1.2/agriculture.php");
HttpResponse response=httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
}catch(IOException e){
e.printStackTrace();
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
result+=line;
}
is.close();
//result=sb.toString();
}catch(Exception e){
e.printStackTrace();
}
try{
JSONObject jsono = new JSONObject(result);
JSONArray jArray = jsono.getJSONArray("actors");
for(int i=0;i<jArray.length();i++){
JSONObject jsonObject=jArray.getJSONObject(i);
list.add(jsonObject.getString("name"));
}
}
catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result){
listItems.addAll(list);
adapter=new ArrayAdapter<String>(this,R.layout.spinner_layout,R.id.txt,listItems);
sp.setAdapter(adapter);
}
}
try this. set adapter after your listitem is filled. If this doesn't work feel free to ask.
Spinners are quite easy to implement -
1) Fetch your data in an ArrayList from SQLite DB.
2) Create a spinner - Spinner abcd;
3) Create an ArrayAdapter with the ArrayList that you defined.
4) Make adapter a drop down - myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
5) Set the adapter of the spinner to the ArrayAdapter- abcd.setAdapter(myAdapter).

Android ListView duplicates data after pressing back button

I have a listview populated by the data from mysql database. It works fine but when I select an item then press back , the previous listview fecth again data from database that duplicates the items in my listview.
Here's is my code :
public class CityPage extends Activity{
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
CityAdapter cityAdapter;
ListView listCity;
ArrayList<City> records;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_page);
context = this;
records = new ArrayList<City>();
listCity = (ListView) findViewById(R.id.cities);
cityAdapter = new CityAdapter(context, R.layout.city_layout, R.id.city_name, records);
listCity.setAdapter(cityAdapter);
listCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(view.getContext(),City_attractions.class);
Toast.makeText(CityPage.this, "Opening", Toast.LENGTH_LONG).show();
String info1 = records.get(position).getCityName();
String info2 = records.get(position).getDescription();
myIntent.putExtra("info1", info1);
myIntent.putExtra("info2", info2);
startActivity(myIntent);
}
});
}
#Override
protected void onStart() {
super.onStart();
fetchCity fetch = new fetchCity();
fetch.execute();
}
private class fetchCity extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://iguideph-001-site1.btempurl.com/getcity.php");
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (Exception e) {
if (pd != null)
pd.dismiss(); //close the dialog if error occurs
Log.e("ERROR", e.getMessage());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("ERROR", "Error converting result " + e.toString());
}
//parse json data
try {
// Remove unexpected characters that might be added to beginning of the string
result = result.substring(result.indexOf(""));
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
City p = new City();
p.setCityName(json_data.getString("place_name"));
p.setDescription(json_data.getString("description"));
records.add(p);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
if (pd != null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
cityAdapter.notifyDataSetChanged(); //notify the ListView to get new records
}
}
}
try remove those lines from onstart() and put them inside oncreate() function
fetchCity fetch = new fetchCity();
fetch.execute();
Good luck !

How to put data in listview which received using AsyncTask?

I am successfully retrieving but unable to put data into listview. how to update ui thread
after retrieving data.
here is the class of asynctask that retrieves data
I tried to update in onPostExecute but couldn't succeed.
class GetJson extends AsyncTask<String, Integer, ArrayList<RowItem>> {
ArrayList<RowItem> rowItems = new ArrayList<RowItem>();
//ArrayList<ArrayList<String>> fullscreens = new ArrayList<ArrayList<String>>() ;
public AsyncResponse delegate = null;
private CustomListViewAdapter arrayadapter;
private ProgressDialog pDialog;
private Context Mycontext;
private ArrayList<String> alist;
private ListView listView;
public GetJson(Context cnxt,ArrayList<String> alist, CustomListViewAdapter adapt,ListView listView) {
Mycontext = cnxt ;
//this.rowItems = rowItems;
this.alist = alist;
this.listView = listView;
}
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
this.pDialog = new ProgressDialog(Mycontext);
this.pDialog.setMessage("Please wait..");
this.pDialog.setIndeterminate(true);
this.pDialog.setCancelable(false);
this.pDialog.show();
//alist.add("fifa");
}
#Override
protected ArrayList<RowItem> doInBackground(String... passing) {
here i am recieving data
return rowItems;
}
#Override
protected void onPostExecute(ArrayList<RowItem> Items) {
super.onPostExecute(Items);
this.pDialog.dismiss();
}
}
I laso tried runuithread in doinBackgroung method
there also i am getting runtime errors
here is my code
protected Void doInBackground(Void... unused) {
runOnUiThread(new Runnable() {
public void run() {
String result = null;
InputStream is = null;
JSONObject json_data=null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
JSONArray ja = new JSONArray();
List<NameValuePair> params = new LinkedList<NameValuePair>();
for(String s : alist)
{
Log.d("s",s);
params.add(new BasicNameValuePair("list[]",s));
}
try{
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
// 2. make POST request to the given URL
HttpGet httpPost = new HttpGet("http://10.0.3.2/infogamma/getapps.php?"+paramString);
// 4. convert JSONObject to JSON to String
String json = ja.toString();
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
//String json = EntityUtils.toString();
is = entity.getContent();
// Log.d("response", ");
}
catch(Exception e){
Log.i("taghttppost",""+e.toString());
}
//parse response
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder stringbuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringbuilder.append(line + "\n");
}
is.close();
result = stringbuilder.toString();
Log.d("ans",result);
}
catch(Exception e)
{
Log.i("tagconvertstr",""+e.toString());
}
//get json data
try{
//JSONObject json = new JSONObject(result);
JSONArray jArray = new JSONArray(result);
Log.d("app_lentgh", Integer.toString(jArray.length()));
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
// this.donnees.add("title: "+ json_data.getString("title") + " appid: " + json_data.getString("appid") );
try{
//commmand http
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://10.0.3.2/infogamma/getAppDetails.php?appid="+json_data.getString("appid"));
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
//String json = EntityUtils.toString();
is = entity.getContent();
// Log.d("response", ");
}
catch(Exception e){
Log.i("taghttppost",""+e.toString());
}
//parse response
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.d("ans",result);
}
catch(Exception e)
{
Log.i("tagconvertstr",""+e.toString());
}
ArrayList<String> screenitem = new ArrayList<String>();
try{
JSONObject j = new JSONObject(result);
screenitem.add(j.getString("scr1"));
screenitem.add(j.getString("scr2"));
screenitem.add(j.getString("scr3"));
// this.fullscreens.add(screenitem);
// RowItem(ImageView imageId, String title, String desc,String catgs,String downloads,String rating,String discription)
RowItem item = new RowItem(j.getString("coverimage"), j.getString("title"), j.getString("category"),j.getString("downloads"),j.getString("rating"),
j.getString("scr1"),j.getString("scr2"),j.getString("scr3"),j.getString("discription"),j.getString("developer"),j.getString("price")
,json_data.getString("appid"));
rowItems.add(item);
}
catch(JSONException e){
Log.i("tagjsonexp",""+e.toString());
}
//SharedPreferences.Editor editor = ((Activity) Mycontext).getPreferences(Mycontext.MODE_PRIVATE).edit();
//editor.;
//editor.commit();
//Log.i("title",json_data.getString("title"));
}
}
catch(JSONException e){
Log.i("tagjsonexp",""+e.toString());
} catch (ParseException e) {
Log.i("tagjsonpars",""+e.toString());
}
adapt = new CustomListViewAdapter(getApplicationContext(),
R.layout.list_item, rowItems);
listView.setAdapter(adapt);
}});
return (null);
}
You can populate the list view from doInBackground by this code
runOnUiThread(new Runnable() {
public void run() {
//set listview Adapter here
}
});
this thing is not preferable. One more thing you can do is create a class which can hold the data you want to show on the item of a list and pass the array of that class object to onPostExecute method from where you can handle the UI thread.
Do it in onPostExecute() or if you want to add them from doInBackground() instantly, do it using runOnUiThread().
Edit:
After reading your comments, You are using CustomListViewAdapter, do you have a constructor with Context,int,ArrayList<String> as parameters in your adapter class?

How to show huge data in listview in android using Async without OnScrollListener

I want to show huge data (+50,000 records) in android listview using Async.
The data comes from web services(dot net) in pages(1000 records in each page).
As I get 1000 records I have to update the listview automatically (without scrolling).This process continues till all the records are fetched.
Am able to fetch all the records but unable to update listview.
My code is :
class XYZ extends AsyncTask<String, Integer, String>
{
#Override
protected String doInBackground(String... params) {
for(int i=1;i<=noOfPagesFromServer;i++)
{
String url="http://182.72.123.138:9523/Service.svc/GetData/"+i;
try
{
HttpGet get =new HttpGet(url );
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(get);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
String responseString = stringBuilder.toString();
JSONObject serverJSONObj = new JSONObject(responseString);
JSONArray serverJSONArray = serverJSONObj .getJSONArray("ABC");
for(int l=0;l<serverJSONArray.length();l++)
{
JSONObject tempJSONObject=serverJSONArray.getJSONObject(l);
a = tempJSONObject.getString("A");
b =tempJSONObject.getString("B");
Model model=new Model(a,b);
arrayList.add(model);}
} catch (Exception e) {
e.printStackTrace();
}
publishProgress(null);
SystemClock.sleep(6000);
}return null;}
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
adapter1 = new CustomListViewAdapter(SearchActivity.this,R.layout.row,arrayList);
listView.setAdapter(adapter1);
listView.this.adapter1.notifyDataSetChanged();
}
#Override
protected void onPostExecute(String result) {
try{
super.onPostExecute(result);
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter1 = new CustomListViewAdapter(SearchActivity.this,R.layout.row,arrayList);
adapter1.notifyDataSetChanged();
listView.setAdapter(adapter1);
}
});
}
catch(Exception e){
e.printStackTrace();
}
}
Thanks for your replies
You can use onProgressUpdate() and acheive the required result...update your model once you receive the 1000 records and update the list...

in AsyncTask i want the data in list view

hi friends i just want the data show in a list view i using async task and i complete get the data in json and filtering it by id and title now i show id and title in a listview can you help me thanks in advance
public class runActivity extends Activity implements OnClickListener {
String returnString="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.1.156/recess/document/document.json");
HttpClient client = new DefaultHttpClient();
HttpResponse response=null;
try{
response = client.execute(httpGet);}
catch(Exception e){}
System.out.println(response.getStatusLine());
String text = null;
try {
response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
String var =text;
try{
JSONObject jObj = new JSONObject(var);
JSONArray jArray = jObj.getJSONArray("document");
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getString("id")+
", title: "+json_data.getString("title")
);
returnString += "\n" +"id:"+ json_data.getString("id")+" "+"Title:"+ json_data.getString("title");
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
protected void onPostExecute(String results) {
if (results!=null) {
ListView listView = (ListView) findViewById(R.id.mylist);
listView.setFilterText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
You will need to build an Array to use with ListAdapter.
Here is a guide from Google: http://developer.android.com/resources/tutorials/views/hello-listview.html
I think the best solution would be to create a Handler in your activity. You can then send a message to the handler and get the data and put it in the ListView.
In doInBackground "for" loop just either create the array of your data or put data in Array list of object (then need to write custom adapter)
for
1- option
http://www.java-samples.com/showtutorial.php?tutorialid=1516
http://www.ezzylearning.com/tutorial.aspx?tid=1659127&q=binding-android-listview-with-string-array-using-arrayadapter
For
2- option
http://www.ezzylearning.com/tutorial.aspx?tid=1763429&q=customizing-android-listview-items-with-custom-arrayadapter

Categories

Resources