I want to declare arrayList into this line:
public class tlcity extends Activity {
//ArrayList<String> idArray = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
and into the other method,for example this method:
protected void onPostExecute(String result) {
//fill the arraylist
...
and into the other method for example this method read arraylist data:
public void readlist(){
//read the arraylist data and show
}
How can i do this?
You can declare ArrayList like this
ArrayList<String> list;
list = new ArrayList<String>();
You can add, remove items in ArrayList Like this
list.add("A");
list.remove(0);
ArrayList<String> abc=new ArrayList<String>();
You can initialize or create an instance of your array list like this
idArray = new ArrayList();
You can perform any operations to it using idArray object.
For example you can add items like this
idArray.add("item1");//In you case its a list of strings.
In the same way you would do that in another Java app / class:
public class tlcity extends Activity {
List<String> idArray;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
idArray = new ArrayList<String>();
}
protected void onPostExecute(String result) {
idArray.add("One");
idArray.add("Two");
idArray.add("Three");
...
}
public void readlist(){
for (final String element : idArray) {
// Use the nth string
}
}
I want to declare arrayList into this line:
ArrayList<String> myList;
and into the other method,for example this method:
myList = new ArrayList<String>;
and into the other method for example this method read arraylist data:
for(int i=0; i<myList.size(); i++)
System.out.println(myList.get(i).toString());
If you want to use ArrayList locally then declare it locally. if you want to use it in all methods then declare it globally in class.
public class tlcity extends Activity {
ArrayList<String> idArray = new ArrayList<>(); // to Use this arraylist globally.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> localaraaylist = new ArrayList<>(); //to use arraylist in only in oncreate method.
....
According to your post, telling how to declae ArrayList will not enough as you have some methods like onPreExecute() which is a method ofAsyncTask Interface.
Look at this,
public class MainActivity extends ActionBarActivity {
ArrayList<String> arrayList; // declaring ArrayList here
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayList = new ArrayList<String>(); // Initializing arrayList
arrayList.add("initial text"); // adding a data to arrayList
ListView listView = (ListView)findViewById(R.id.listView);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arrayList); // setting the arrayList in ArrayAdapter
listView.setAdapter(adapter);
new LongOperation().execute(); // async Task
}
private class LongOperation extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
// progress dialog starts here
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
// for understanding purpose, i made a thread to sleep for 5 sec and later it will add A,B & C to ArrayList.
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// adding few more items to arrayList
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss(); // dismissing the progress Dialog
adapter.notifyDataSetChanged(); // refreshing listview
readA(); // read the arrayList
}
}
public void readA()
{
for (int i = 0; i<arrayList.size(); i++)
{
Log.d("key",arrayList.get(i));
}
}
}
Output :
If you run the above code, Initially your list view will only contain only one item & after 5 sec loading it will add another 3 items. The below information will print in logcat that reads the ArrayList.
04-13 14:07:32.395 1123-1123/? D/key﹕ initial text
04-13 14:07:32.395 1123-1123/? D/key﹕ A
04-13 14:07:32.395 1123-1123/? D/key﹕ B
04-13 14:07:32.395 1123-1123/? D/key﹕ C
Related
I wanna add items to my list but it only shows the first one:
public class MainActivity extends Activity {
Server server;
TextView infoip, msg;
TextView usersTitle;
String[] array = {"a"};
ArrayList<String> lst;
ArrayAdapter<String> adapter;
ListView userList;
#Override
public void onCreate(Bundle savedInstanceState) {
lst = new ArrayList<String>(Arrays.asList(array));
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lst);
userList = (ListView) findViewById(R.id.userList);
userList.setAdapter(adapter);
From this other class method, everytime it is called I want the text to go below the first one. The method certainly runs but it does not put the text below the previous one. It just shows "a"! Anyone knows why?
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.lst.add(message);
activity.adapter.notifyDataSetChanged();
}
});
I have also tried:
adapter.insert(String, int);
lst.add(int, String);
And even added in the onCreate method this:
lst.add(1, "2");
adapter.notifyDataSetChanged();
And still doesnt add the "2"!!
If you are adding items to Arraylist from another class ,you have to declare your Arraylist Static.So that it can hold items in memory.
Replace ArrayList lst with public static ArrayList
Here is the solution to your Problem.I have created an Activity class and Tests java class.
public class MainActivity extends Activity {
String[] array = {"a"};
public static ArrayList<String> lst;
ArrayAdapter<String> adapter;
ListView userList;
Tests tests = new Tests();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userList = (ListView) findViewById(R.id.userList);
lst = new ArrayList<String>(Arrays.asList(array));
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lst);
userList.setAdapter(adapter);
tests.callThread();
}
}
Here is the Tests.java Class
public class Tests {
int i = 0;
String message = "";
Thread runOnUiThread;
public void callThread()
{
new Thread(new Runnable() {
#Override
public void run() {
try {
while (i < 10) {
i = i + 1;
message = String.valueOf(i);
//Create a server socket object and bind it to a port
MainActivity.lst.add(message);
}
}catch(Exception e){
e.printStackTrace();
}
}
}).start();
}
}
Just call your service inside this thread where I have incremented variable i and by this way you can populate the list in right order.
Can you tell whether the other class is Activity or Fragment ?
And while adding the data into Arraylist, you don't need the Thread to be run in order to insert new data to Arraylist
Try to make "lst" and "adapter" both static.
I'm suspicious about the runOnUiThread. Can you provide more information why did you use this function? Also i highly recommend using RecyclerView
Also you can refer to this post for adding items to RecyclerView
I know this Question asked so many times but i cant find mistake
I was checked all things what is am doing wrong but I cant find what I did mistake.
I am using back4App for back end.
I am just retrieve data from that and just want to show in my listview.
I was set log to check data which i am retrieving so it show arraylist size perfect in doInbackground method. but when I return it to postexecute and there i am also check size of it.but it show 0 there.
dont know what mistake i was did.
My code is below:
public class HomeActivity extends AppCompatActivity {
ProgressDialog mProgressDialog;
ArrayList<String> items;
ListView listView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
listView = (ListView) findViewById(R.id.listview);
items=new ArrayList<>();
new GetServices().execute();
}
private class GetServices extends AsyncTask<Void, Void, ArrayList<String>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(HomeActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Parse.com Simple ListView Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected ArrayList<String> doInBackground(Void... params) {
// Locate the class table named "services" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("services");
query.orderByAscending("updatedAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
items.clear();
Log.i("TAG", "datasize=>" + objects.size());
List<String> temp = new ArrayList<String>();
for (ParseObject services : objects) {
temp.clear();
items.add(services.getString("serviceTitle"));
temp = services.getList("serviceDetails");
items.add(Util.getHtmlText(temp));
}
Log.i("TAG", "itemsize=>" + items.size());
} else {
e.printStackTrace();
}
}
});
return items;
}
#Override
protected void onPostExecute(ArrayList<String> strings) {
super.onPostExecute(strings);
Log.i("TAG", "resultsize=>" + strings.size());
for (int i = 0; i < strings.size(); i++) {
Log.i("TAG", "==>" + strings.get(i));
}
// Pass the results into an ArrayAdapter
CustomServiceListAdapter adapter = new CustomServiceListAdapter(HomeActivity.this, R.layout.custom_fragment_service_list_item, strings);
// Binds the Adapter to the ListView
listView.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
// Capture button clicks on ListView items
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Send single item click data to SingleItemView Class
Intent i = new Intent(HomeActivity.this,
DetailsActivity.class);
// Pass data "name" followed by the position
i.putExtra("data", items.get(position));
// Open SingleItemView.java Activity
startActivity(i);
}
});
}
}}
My Logcat show below:
05-20 13:10:28.661 19099-19099/com.example.apexweb I/TAG: resultsize=>0
05-20 13:10:29.409 19099-19099/com.example.apexweb I/TAG: datasize=>4
05-20 13:10:29.410 19099-19099/com.example.apexweb I/TAG: itemsize=>8
Accordingly to the documentation findInBackground retrieves a list of ParseObjects that satisfy this query from the source in a background thread, and gets you the results in the callback. doInBackground does not wait until the callback with the results is called. That's why in onPostExecute the size is still 0. Since doInBackground runs already on a different thread, a second level of asynchronously is not necessary. You can call directly find(). Alternatively you can get rid of the AsyncTask and run findInBackground with the callback from the UI Thread
this is my code to load listview items
#SuppressLint("DefaultLocale")
public class SearchList extends Activity {
private ArrayList<String> founded = new ArrayList<String>();
private OrderAdapter m_adapter;
ListView lv;
/** Called when the activity is first created. */
#SuppressLint("DefaultLocale")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchlist);
lv = (ListView) findViewById(R.id.listView1);
new Load().execute();
m_adapter = new OrderAdapter(this, R.layout.itemview, founded);
lv.setAdapter(m_adapter);
lv.setTextFilterEnabled(true);
}
private class Load extends AsyncTask<Void, Void, Void> {
ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = new ProgressDialog(SearchList.this);
progress.setMessage("loading....");
progress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
for (int i = 0; i <500000; i++) {
founded.add("String "+i);
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// write display tracks logic here
progress.dismiss(); // dismiss dialog
}
}
when i run the code the progress dialog already appear but after its dismiss i found that the list is empty no items added to it i do not know what is the problem and why the list is empty after the dialog loading .Pls need help
thanks in advance.
Set listadapter in onPostExecute Because you Are using AsyncTask to get adapter data and setting ListAdapter before Completing AsyncTask So Try to Set ListAdapter after Completing AsyncTask
So add these
m_adapter = new OrderAdapter(this, R.layout.itemview, founded);
lv.setAdapter(m_adapter);
lv.setTextFilterEnabled(true);
lines in onPostExecute method instead of onCreate Method
#Override
protected void onPostExecute(Void result) {
// write display tracks logic here
progress.dismiss(); // dismiss dialog
m_adapter = new OrderAdapter(YourActivity.this, R.layout.itemview, founded);
lv.setAdapter(m_adapter);
lv.setTextFilterEnabled(true);
}
In my main activity I got an arraylist called data. I call an asynctask and do some stuff that gives me a different arraylist called values.
In the post execute of the asynctask I want to use items in 'values' to add some objects to 'data'. However, when debugging I noticed that the objects dont get added.
public class MainActivity extends Activity
{
ArrayList<DataItem> data;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data = new ArrayList<DataItem>();
update();
}
public void update()
{
AsyncCallAWS thisTask = new AsyncCallAWS();
thisTask.execute();
}
private class AsyncCallAWS extends AsyncTask<String, Void, Void>
{
ArrayList<String> values = new ArrayList<String>();
protected void onPostExecute(Void result)
{
Log.i(TAG, "onPostExecute");
DataItem d;
for(String s : values)
{
d = new DataItem();
d.setValue(s);
d.setDataStreamName("test");
data.add(d);
}
}
//code to fill array
I'm guessing it's because I try to add items from the asynctask? Idk how to solve this, I need the data arraylist for a listview.
In AsyncTask class override method onProgressUpdate(), where you will add elements to array. Then in doInBackground() call publishProgress() for sending elements to onProgressUpdate(). Here http://developer.android.com/reference/android/os/AsyncTask.html -is great example.
private class TestAsyncTask extends AsyncTask<Object, String, Object> {
#Override
protected Object doInBackground(Object... params) {
String item = "";
//Do some stuff
publishProgress(item);
return null;
}
#Override
public void onProgressUpdate(String... value) {
data.add(value[0]);
}
#Override
protected void onPostExecute(Object result) {
}
}
I dont think you should create objects in the onPostExecute-method. Instead create it in the doInBackground-method of the class that extends AsyncTask, and then use set-methods in the onPostExecute-metod.
I need to retrieve some huge data from one database when an activity is started. To prevent a user with a frozen window, I decided to run a ProgressDialog while data is being processed.
From OnCreate I call my initDb Class:
new initDb().execute();
And then to do this I have one class inside my activity's class:
public class initDb extends AsyncTask<Void, Void, Void> {
ProgressDialog mDialog = new ProgressDialog(ClientsReg.this);
#Override
protected void onPreExecute() {
mDialog.setMessage("Please wait...");
mDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
opendb();
listCities();
return null;
}
#Override
protected void onPostExecute(Void unused) {
// Pass the result data back to the main activity
mDialog.dismiss();
}
}
The real problem happens while setting the adapter:
private void listCities() {
mRedrawHandler.sleep(100000);
c = db.executeSQL("SELECT * FROM RegDB WHERE Reg_Type = 1 AND cad_uzkow = 0 ORDER BY _id DESC");
//add some list items
ArrayList<String> finalList = new ArrayList<String>();
c.moveToFirst();
while (!c.isAfterLast()){
finalList.add(c.getString(0) + ")"+ c.getString(5));
c.moveToNext();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.row, R.id.itemShow, finalList);
sp.setAdapter(adapter);
}
It always happen to crash on sp.setAdapter(adapter);
Any ideas?
Thank you!
Try taking the finalList as an attribute of your initDb class this way you can populate it on the doInBackground method and then us it on the onPostExecute, like this:
public class initDb extends AsyncTask<Void, Void, Void> {
ProgressDialog mDialog = new ProgressDialog(ClientsReg.this);
ArrayList<String> finalList;
#Override
protected void onPreExecute() {
mDialog.setMessage("Please wait...");
mDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
opendb();
listCities();
return null;
}
#Override
protected void onPostExecute(Void unused) {
// Pass the result data back to the main activity
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.row, R.id.itemShow, finalList);
sp.setAdapter(adapter);
mDialog.dismiss();
}
private void listCities() {
mRedrawHandler.sleep(100000);
c = db.executeSQL("SELECT * FROM RegDB WHERE Reg_Type = 1 AND cad_uzkow = 0 ORDER BY _id DESC");
//add some list items
finalList = new ArrayList<String>();
c.moveToFirst();
while (!c.isAfterLast()){
finalList.add(c.getString(0) + ")"+ c.getString(5));
c.moveToNext();
}
}
You should call:
sp.setAdapter(adapter);
in main UI thread. For example in onPostExecute() function. Always keep in mind that views (such as ListView) should only be accessed from main thread.
You can't access the UI from other thread than the thread that created the UI. So in AsyncTask, you can't use doInBackground() for this purpose.