Json Data reload again on configuration changes in background tasks - android

I have made an app Earthquake Report app. in that I am fetching earthquake data through an API and showing it in recycler view.
This process runs on the background thread by using the Executor service method and runnable.
But when I run my app and when I rotated my phone the background process is re-executed and reloads data .
How to prevent it? I am using Java for making app.
RecyclerView recyclerView;
LinearLayout nointernetLinearLayout;
ArrayList<EarthquakeModel> earthquake;
private ImageView mEmptyView;
private Button mNoInternetButton;
boolean isConnected;
private static final String url = "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2021-09-10&endtime=2021-09-11";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
nointernetLinearLayout = findViewById(R.id.no_internet);
mEmptyView = findViewById(R.id.empty_view);
earthquake = new ArrayList<>();
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(new Runnable() {
#Override
public void run() {
QueryUtils queryUtils = new QueryUtils();
String json = queryUtils.call(url);
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (isConnected){
Log.i("This is background task","it is restarted if showing again");
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("features");
for (int i=0; i<jsonArray.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
JSONObject properties = c.getJSONObject("properties");
double magnitude = properties.getDouble("mag");
String location = properties.getString("place");
long time = properties.getLong("time");
String url = properties.getString("url");
EarthquakeModel earthquakeModel = new EarthquakeModel(location, magnitude,time,url);
earthquake.add(earthquakeModel);
}
}
}catch (JSONException e){
Log.e("Error","is"+e.getMessage());
}
runOnUiThread(new Runnable() {
#Override
public void run() {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
if (isConnected&&!earthquake.isEmpty()){
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
EarthquakeAdapter earthquakeAdapter = new EarthquakeAdapter(earthquake,MainActivity.this);
recyclerView.setAdapter(earthquakeAdapter);
}if(isConnected&&earthquake.isEmpty()){
recyclerView.setVisibility(View.GONE);
mEmptyView.setVisibility(View.VISIBLE);
}
if (!isConnected){
recyclerView.setVisibility(View.GONE);
nointernetLinearLayout.setVisibility(View.VISIBLE);
}
});
}
});
}

Run the service in your viewModel, since the viewmodel survives the configuration change.
The update the UI with LiveData.
public ExampleViewModel extends ViewModel {
private MutableLiveData<ArrayList<EarthquakeModel>> earthquake;
public ExampleViewModel() {
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(new Runnable() {
//get data
earthquake.post(someData)
}
}
public LiveData<ArrayList<EarthquakeModel>> getEarthQuake() {
return earthquake;
}
}
Then in your Activity observe the LiveData
public class ExampleActivity extends Activity {
private ExampleViewModel exampleViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
exampleViewModel = new ViewModelProvider(this).get(ExampleViewModel.class);
exampleViewModel.getEarthQuake().observe(getViewLifecycleOwner(), array -> {
//do somthing with array
}
}
}

Related

How do I save adapter content in a recycler view so when I close the app and restart the adapter is the same

This is my main activity so far
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
private List<userTask> tasklist= new ArrayList<>();
private userTaskAdapter adapter;
//private Context context;
private static Bundle mBundleState;
private final String KEY_RECYCLER_STATE = "recycler_state";
private Parcelable listState;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycleOne);
recyclerView.setHasFixedSize(true);
adapter = new userTaskAdapter(tasklist);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
preparetestdata();
}
private void preparetestdata()
{
String data = "";
try {
InputStream fis = MainActivity.this.getResources().getAssets().open("task.txt");
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((data = br.readLine()) != null)
{
String delims = "[:]+";
String[] temp = data.split(delims);
String tempTask = new String();
String tempDescription = new String();
for (int i=0; i < temp.length; i++)
{
if(i == 0)
tempTask = temp[i];
else
tempDescription = temp[i];
}
userTask tempUser = new userTask(tempTask, tempDescription);
tasklist.add(tempUser);
}
} catch (IOException e)
{
e.printStackTrace();
}
}
/**
* This function will add new task to task list
* #param v
*/
public void onAdd(View v)
{
EditText editTaskTitle = (EditText) findViewById(R.id.taskTitle);
EditText editDescription = (EditText) findViewById(R.id.taskDescription);
String tname = editTaskTitle.getText().toString();
String tdescrip = editDescription.getText().toString();
userTask task = new userTask(tname, tdescrip);
tasklist.add(task);
Log.d("Tname :", tname);
Log.d("tdescription :", tdescrip);
try {
FileOutputStream stream = new FileOutputStream(new File(getFilesDir(), "task.txt"));
int counter =0;
for (int i =0; i < tasklist.size(); i++)
{
String total = tasklist.get(i).getTName() + " : " + tasklist.get(i).getTDescrip() + "\n";
stream.write(total.getBytes());
counter++;
}
Toast.makeText(this, "got here", Toast.LENGTH_SHORT).show();
stream.close();
adapter.notifyDataSetChanged();
//recyclerView
Log.d("UpList", String.valueOf(counter));
}catch(IOException e) {
e.printStackTrace();
}
}
/**
#Override
protected void onSaveInstanceState(Bundle state)
{
super.onSaveInstanceState(state);
//state.putSerializable("listdata", adapter.);
}**/
#Override
public void onStop()
{
super.onStop();
mBundleState = new Bundle();
listState = recyclerView.getLayoutManager().onSaveInstanceState();
mBundleState.putParcelable(KEY_RECYCLER_STATE, listState);
}
#Override
public void onResume()
{
super.onResume();
if (mBundleState != null)
{
listState = mBundleState.getParcelable(KEY_RECYCLER_STATE);
recyclerView.getLayoutManager().onRestoreInstanceState(listState);
}
}
When I add a new task and exits the app that new task will still be in the recycler view. But when I close the app that new task will not still be in the recycler view. I was thinking of saving the state of the adapter but am not really sure how to do this. I tried to do the serializable method but adapters are not serialable

Android JSON Data not Displayed in ListView ( Using Realm )

im trying to get data from a server inform of JSON and im storing the data to my offline database ( in this case : Realm ), whenever i try to retrieve the data, nothing is displayed in the listview.
public class MainActivity extends AppCompatActivity {
public static ListView myList;
public static ListAdapter myAdapter;
public static Realm realm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Realm.init(this);
realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmResults<Recipe> dRecipies = realm.where(Recipe.class).findAll();
if(dRecipies!= null)dRecipies.deleteAllFromRealm();
}
});
DownloadTask newTask = new DownloadTask();
newTask.execute("hi");
setContentView(R.layout.activity_main);
myList = (ListView) findViewById(R.id.Recipe_list);
// getData();
setDisplay();
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String p = String.valueOf(position);
Intent in = new Intent(MainActivity.this, SecondScreenDetails.class);
in.putExtra("Position", p);
startActivity(in);
}
});
}
public void setDisplay(){
ArrayList<Recipe> finalRecipies = new ArrayList<>();
RealmResults<Recipe> rrRecipies = realm.where(Recipe.class).findAll();
for(Recipe r: rrRecipies){
finalRecipies.add(r);
Toast.makeText(this, r.getName(), Toast.LENGTH_SHORT).show();
}
myAdapter = new ListViewAdapter(this, finalRecipies);
myList.setAdapter(myAdapter);
}
#Override
protected void onDestroy() {
realm.close();
super.onDestroy();
}
}
im doing this because, if i dont, the data keeps getting repeatedly stored, resulting in repetition.
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmResults<Recipe> dRecipies = realm.where(Recipe.class).findAll();
if(dRecipies!= null)dRecipies.deleteAllFromRealm();
}
});
when i tried without actually deleting the data, then the Toast in the
setDisplay() method is working and the data is being shown.(Toasts are repeated as i open the app second time, it gets twice... etc)
When i insert this, even the toasts dont show up.
My download activity
public class DownloadTask extends AsyncTask<String,Void,String> {
private RealmList<Recipe> realmRecipe = new RealmList<>();
String result;
#Override
protected String doInBackground(String... params) {
result = "";
Realm realm = null;
realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json").build();
try {
result = client.newCall(request).execute().body().string();
Log.i("RESULT", result);
JSONArray rootArray = new JSONArray(result);
for (int i = 0; i < rootArray.length(); i++) {
JSONObject tempObject = rootArray.getJSONObject(i);
JSONArray jIngredients = tempObject.getJSONArray("ingredients");
JSONArray jSteps = tempObject.getJSONArray("steps");
// Get the ingredients
List<Ingredients> ingredients = new ArrayList<>();
for (int j = 0; j < jIngredients.length(); j++) {
JSONObject tempIngredient = jIngredients.getJSONObject(j);
Ingredients nIngredient = realm.createObject(Ingredients.class);
nIngredient.setIngredient(tempIngredient.getString("ingredient"));
nIngredient.setMeasure(tempIngredient.getString("measure"));
nIngredient.setQuantity(tempIngredient.getString("quantity"));
// Ingredients newIngredient = new Ingredients(tempIngredient.getString("quantity"),
// tempIngredient.getString("measure"),
// tempIngredient.getString("ingredient"));
// ingredients.add(newIngredient);
ingredients.add(nIngredient);
}
// Get the steps
List<Steps> steps = new ArrayList<>();
for (int j = 0; j < jSteps.length(); j++) {
JSONObject tempStep = jSteps.getJSONObject(j);
Steps nStep = realm.createObject(Steps.class);
nStep.setDescription(tempStep.getString("description"));
nStep.setId(tempStep.getString("id"));
nStep.setShortDescription(tempStep.getString("shortDescription"));
nStep.setVideoURL(tempStep.getString("videoURL"));
steps.add(nStep);
// Steps newStep = new Steps(tempStep.getString("id"), tempStep.getString("shortDescription"),
// tempStep.getString("description"), tempStep.getString("videoURL"));
// steps.add(newStep);
}
// Create the recipe
Recipe nRecipe = realm.createObject(Recipe.class);
nRecipe.setId(tempObject.getString("id"));
nRecipe.setName(tempObject.getString("name"));
nRecipe.setServings(tempObject.getString("servings"));
nRecipe.setIngredients(ingredients);
nRecipe.setSteps(steps);
realmRecipe.add(nRecipe);
// Recipe newRecipe = new Recipe(tempObject.getString("id"), tempObject.getString("name"), tempObject.getString("servings"), ingredients, steps);
// MainActivity.mRecipies.add(newRecipe);
}
}catch (Exception e){
Log.i("Error Message", e.getMessage());
}
}
});
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}

AsyncTask not starting after device rotate even after object re-creation

I have a REST server that spits out data from a remote ADC, and I need to graph the data just for presentation. I used AsyncTask to move the data aquisition off of the main thread to prevent NetworkOnMainThreadException. I wrote this:
package inostiot.inostiot;
// imports
public class MonitorActivity extends AppCompatActivity {
private GraphWorker worker;
#Override
protected void onSaveInstanceState(Bundle outState) {
worker.cancel(true);
outState.putBundle("state", worker.prepareResume());
outState.putBoolean("resuming", true);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monitor);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String ip = extras.getString("ip");
LineChart chart = (LineChart) findViewById(R.id.chart);
XAxis x = chart.getXAxis();
YAxis y = chart.getAxisLeft();
// More chart setup here, ignore
if (savedInstanceState != null) {
boolean resuming = savedInstanceState.getBoolean("resuming", false);
if (resuming) {
worker = new GraphWorker(this, ip, chart, true);
worker.resume(savedInstanceState.getBundle("state"));
worker.execute();
}
} else {
worker = new GraphWorker(this, ip, chart, false);
worker.execute();
}
}
}
class GraphWorker extends AsyncTask<Void, Object, Void> {
private LineChart chart;
private boolean resuming;
private boolean running = true;
private String ip;
private Activity parent;
private ArrayList<ADCPort> ports;
private ArrayList<WalkingDataset> walkingDatasets;
private ArrayList<LineDataSet> lineDataSets;
GraphWorker(Activity parent, String ip, LineChart chart, boolean resuming) {
this.parent = parent;
if (!resuming) {
ports = new ArrayList<>();
walkingDatasets = new ArrayList<>();
this.ip = ip;
}
this.chart = chart;
this.resuming = resuming;
lineDataSets = new ArrayList<>();
}
#Override
public Void doInBackground(Void...params) {
ADC adc = new ADC(ip);
if (!resuming) {
if (!adc.auth()) throw new RuntimeException("Server invalid!");
ports.add(new ColoredADCPort(0, "#FF0000"));
walkingDatasets.add(new WalkingDataset(10));
// More ports are initialized here, just copy-paste an
// color change
}
while (running) {
try {
ports = adc.readPorts(ports);
publishProgress((Object)ports);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (ADCException e) {
e.printStackTrace();
break;
}
}
return null;
}
void resume(Bundle data) {
this.ports = (ArrayList<ADCPort>) data.getSerializable("ports");
this.walkingDatasets = (ArrayList<WalkingDataset>) data.getSerializable("walkingDatasets");
this.ip = data.getString("ip");
this.chart.invalidate();
}
Bundle prepareResume() {
Bundle data = new Bundle();
data.putSerializable("ports", ports);
data.putSerializable("walkingDatasets", walkingDatasets);
data.putString("ip", ip);
return data;
}
#Override
protected void onProgressUpdate(Object... values) {
ArrayList<ADCPort> ports = (ArrayList<ADCPort>) values[0];
lineDataSets.clear();
for (int i = 0; i < ports.size(); i++) {
ColoredADCPort port = (ColoredADCPort) ports.get(i);
WalkingDataset dataset = walkingDatasets.get(i);
dataset.add(port.getValue());
LineDataSet lineDataSet = new LineDataSet(dataset, String.format(Locale.ENGLISH, "Sensor %d", i));
lineDataSet.setCircleColor(Color.parseColor(port.getColor()));
lineDataSet.setColor(Color.parseColor(port.getColor()));
lineDataSet.setDrawValues(false);
lineDataSets.add(lineDataSet);
}
final LineData data = new LineData();
for (LineDataSet set : lineDataSets) {
data.addDataSet(set);
}
chart.setData(data);
chart.postInvalidate();
super.onProgressUpdate();
}
public void stopRunner() {
this.running = false;
}
}
There is a LineChart from MPAndroidCharts on the Activity, and the AsyncTask is supposed to update the UI with the new chart data that it gets from the server. However, after a device rotation and after the resume() method of GraphWorker is called to restore the object state, and after calling execute(), doInBackground() is never called or being run. Why?
I need to stop the previous worker before starting another.
In sequential processing all Async tasks run in a single thread and thus have to wait before the previous task ends. If you need to execute code immediately, you need tasks to be processed in parallel in separate threads.
So, adding running=false in prepareResume to stop the previous worker solves this issue.

Getting error:No adapter attached; skipping layout in recyclerview

I tried to fetch the json values from url and shows in listview with adapter in recylerview. but the listview is empty and getting this error 'No adapter attached; skipping layout'. When I tried with the below code its working
for (int i = index; i < end; i++) {
User user = new User();
user.setName("Name " + i);
mUsers.add(user);
}
Here is my part of code, if needed I'll upload complete code
public class OtherNews extends AppCompatActivity {
JSONArray jsonarray;
private RecyclerView mRecyclerView;
private List<User> mUsers = new ArrayList<>();
private UserAdapter mUserAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
mRecyclerView = (RecyclerView) findViewById(R.id.recycleView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mUserAdapter = new UserAdapter();
new DownloadJSON().execute();
mUserAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
Log.e("haint", "Load More");
mUsers.add(null);
mUserAdapter.notifyItemInserted(mUsers.size() - 1);
//Load more data for reyclerview
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Log.e("haint", "Load More 2");
//Remove loading item
mUsers.remove(mUsers.size() - 1);
mUserAdapter.notifyItemRemoved(mUsers.size());
//Load data
int index = mUsers.size();
int end = index + 20;
for (int i = index; i < end; i++) {
User user = new User();
user.setName("Name " + i);
user.setEmail("alibaba" + i + "#gmail.com");
mUsers.add(user);
}
mUserAdapter.notifyDataSetChanged();
mUserAdapter.setLoaded();
}
}, 5000);
}
});
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
private static final String TAG = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall("http://xxxxxxxxx.in/projects/falcon/getallnews.php?page=2");
if (jsonStr != null) {
try {
JSONObject jsonobject = new JSONObject(jsonStr);
jsonarray = jsonobject.getJSONArray("news");
// Getting JSON Array node
for (int i = 0; i < jsonarray.length(); i++) {
User user = new User();
String title = jsonobject.getString("title");
user.setName(title);
mUsers.add(user);
}
} catch (final JSONException e) {
}
} else {
Log.d(TAG, "someOther)");
}
return null;
}
#Override
protected void onPostExecute(Void args) {
mRecyclerView.setAdapter(mUserAdapter);
}
}
I get the value in this line of code, but couldn't set in list view.
String title = jsonobject.getString("title");
user.setName(title);
The issue is exactly like it sounds, an adapter is not being attached when it needs it. You don't attach it until onPostExecute. Just attach it right from the beginning:
mRecyclerView = (RecyclerView) findViewById(R.id.recycleView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mUserAdapter = new UserAdapter();
mRecyclerView.setAdapter(mUserAdapter);
As you modify the adapter in other parts of the code, your RecyclerView will update automatically, so long as you call notifyDataSetChanged() or some related method.

IllegalStateException in AsyncTask. The content of adapter has changed but listview did not receive a notification

I am working on TCP socket. I receive data for every 1 sec from server and I need to display it on screen in ListView.
For this I used AsyncTask.
But I am frequently getting IllegalStateException error
My code:
Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
finalizer = new Runnable() {
public void run() {
try {
if (navBool) {
runOnUiThread(new Runnable() {
public void run() {
new RetriveStock().execute(); // AsyncTask.
}
});
}
} catch (Exception e) {
}
}
};
handler.post(finalizer);
}
};
timer.schedule(doAsynchronousTask, 0, 1000);
// AsyncTask class
public class RetriveStock extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
message = client.clientReceive(1); // Here I receive data from server and stores it in "message" string variable.
printJson(); // FUNCTION WHICH UPDATE VALUES IN 'obj' OBJECT
runOnUiThread(new Runnable() {
#Override
public void run() {
updateList();// FUNCTION WHICH UPDATE THE LISTVIEW UI.
adb.notifyDataSetChanged();
}
});
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
if (adb != null) {
lv.invalidateViews();
lv.setAdapter(adb);
adb.notifyDataSetChanged();
lv.requestLayout();
}
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
// function which update values in JSON.
public void printJson() {
try {
JSONArray jsonArray = new JSONArray(message);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
String symbol = json.getString("Symbol_En");
User obj = new User();
boolean checkSymbol = false;
for (int j = 0; j < list.size(); j++) {
obj = list.get(j);
if (obj.getSymbol().equalsIgnoreCase(symbol)) {
checkSymbol = true;
break;
}
}
if (!checkSymbol) {
obj = new User();
obj.Symbol_En = json.getString("Symbol_En");
obj.Symbol_Ar = json.getString("Symbol_Ar");
obj.AskPrice = json.getString("Ask");
obj.BidPrice = json.getString("Bid");
obj.AskQuantity = json.getString("AskQuantity");
obj.High = json.getString("High");
obj.Low = json.getString("Low");
obj.Open = json.getString("Open");
obj.Close = json.getString("Close");
obj.PerChange = json.getString("PerChange");
obj.NetChange = json.getString("NetChange");
obj.Volume = json.getString("Volume");
obj.Ltp = json.getString("LTP");
obj.TimeStamp = json.getString("TimeStamp");
obj.symbolId = json.getString("Id");
list.add(obj);
} else {
obj.Symbol_En = json.getString("Symbol_En");
obj.AskPrice = json.getString("Ask");
obj.BidPrice = json.getString("Bid");
obj.High = high + "";
obj.Low = low + "";
obj.Open = json.getString("Open");
obj.Close = json.getString("Close");
obj.PerChange = json.getString("PerChange");
obj.NetChange = json.getString("NetChange");
obj.Volume = json.getString("Volume");
obj.Ltp = json.getString("LTP");
obj.TimeStamp = json.getString("TimeStamp");
obj.symbolId = json.getString("Id");
}
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
// function which update LISTVIEW UI.
public void updateList() {
adb = new ArrayAdapter<User>(DefaultMarketWatch.this,
R.layout.rssitemview, list) {
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
View view = convertView;
try {
if (null == view) {
LayoutInflater vi = (LayoutInflater) DefaultMarketWatch.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.rssitemview, null);
}
final User u = list.get(position);
if (null != u) {
final TextView title = (TextView) view
.findViewById(R.id.symbol);
final TextView persend = (TextView) view
.findViewById(R.id.persent);
final TextView ltp = (TextView) view
.findViewById(R.id.ltp);
final TextView high = (TextView) view
.findViewById(R.id.high);
final TextView low = (TextView) view
.findViewById(R.id.low);
final TextView persendBold = (TextView) view
.findViewById(R.id.persent_bold);
final TextView persendSup = (TextView) view
.findViewById(R.id.persent_sup);
ltp.setText(u.getLtp());
title.setText(u.getSymbol());
high.setText(u.getHigh());
low.setText(u.getLow());
persend.setText(u.getPerChange());
}
} catch (Exception e) {
e.printStackTrace();
}
return view;
}
};
}
Your log says
The content of the adapter is changed but listview did not receive notification. make sure content of your adapter is not modified from background thread but only from ui thread.
You have updateList() // FUNCTION WHICH UPDATE THE LISTVIEW UIin doInBackground. doInbackground is invoked on the background thread. You need to update ui on the Ui thread.
Use runOnUiThread which is method of activity or return result in doInbackground and update listview in onPostExecute

Categories

Resources