Hello guys I am doing the delete function in my project and it seems that the notifyDataSetChanged is not working. I've already done some research about this but I don't quiet understand
here is my code in onCreate:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_dropped_student);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
SharedPreferences preferences = getSharedPreferences("MyApp", MODE_PRIVATE);
subj_code = preferences.getString("code", "UNKNOWN");
subj_code_lab = preferences.getString("code_lab", "UNKNOWN");
studentList = new ArrayList<HashMap<String, String>>();
mylistView = (ListView) findViewById(R.id.list);
arrayAdapter = new StudAdapter(this, stud_List);
mylistView.setAdapter(arrayAdapter);
new LoadStudent().execute();
mylistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String studentId = ((TextView) (view.findViewById(R.id.stud_id))).getText().toString();
final String studentName = ((TextView) (view.findViewById(R.id.studName))).getText().toString();
class AttemptGetData extends AsyncTask<String, String, String>{
String code = subj_code.toString();
String id = studentId;
String stud_name = studentName;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewDroppedStudent.this);
pDialog.setMessage("In Progress...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
JSONParser jsonParser = new JSONParser();
String url = null;
try {
url = "http://192.168.22.3/MobileClassRecord/undroppedStudent.php?stud_id="+ URLEncoder.encode(id, "UTF-8")+"&subj_code="+ URLEncoder.encode(subj_code, "UTF-8");
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}
List<NameValuePair> mList = new ArrayList<NameValuePair>();
mList.add(new BasicNameValuePair("stud_id", id));
mList.add(new BasicNameValuePair("subj_code", code));
JSONObject jsonObject = jsonParser.makeHttpRequest(url, "POST", mList);
Log.d("Undrop Student", jsonObject.toString());
try {
verify = jsonObject.getString("Message");
return verify;
}catch (JSONException e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pDialog.dismiss();
if (s != null){
Toast.makeText(getApplicationContext(), verify, Toast.LENGTH_LONG).show();
}
}
}
final MaterialDialog materialDialog = new MaterialDialog(ViewDroppedStudent.this);
materialDialog.setTitle("Undrop Student");
materialDialog.setMessage("Name: " + studentName);
materialDialog.setPositiveButton("UNDROP", new View.OnClickListener() {
#Override
public void onClick(View v) {
materialDialog.dismiss();
new AttemptGetData().execute();
arrayAdapter.notifyDataSetChanged();
}
}).setNegativeButton("CANCEL", new View.OnClickListener() {
#Override
public void onClick(View v) {
materialDialog.dismiss();
}
});
materialDialog.show();
}
});
}
any help would be much appreciated :)
You need to write arrayAdapter.notifyDataSetChanged(); in onPostExecute method
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pDialog.dismiss();
if (s != null){
Toast.makeText(getApplicationContext(), verify, Toast.LENGTH_LONG).show();
}
arrayAdapter.notifyDataSetChanged();
}
Remove perticular data from your stud_List
put arrayAdapter.notifyDataSetChanged(); in onPostExecute()
It is possible that sometime notifiDatasetChanged not works with custom adapter.
you can create custom method in your adapter like below :
public void refresh(ArrayList<HashMap<String, String>> list)
{
this.list=list; //replace this.list with your adapter list variable.
notifyDataSetChanged();
}
call it in onPostExecute()
arrayAdapter.refresh(stud_List);
Your asynctask runs asyncronously so when you call execute() on asynctask it will run in a parallel thread while the execution of main thread continues. So your notifydatasetchanged() is getting called even before your asynctask() is finished. So call notifyDataSetChanged() inside onPostExecute()
Related
I'm having a hard time figuring out how to implement the new MyAsyncTask().execute("") that I've searched because I have separate classes that extends Asynctask. I wanted to call the class everytime i click the button. Hope you guys can help me figure this out.
Here is my MainActivity
public class MainActivity extends AppCompatActivity {
String url = "http://192.168.254.103/dbtest/categories.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.start);
final ListView lv = (ListView) findViewById(R.id.lv);
final Downloader d = new Downloader(this,url,lv);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.execute();
}
});
}
}
Here is my Downloader.java
public class Downloader extends AsyncTask<Void,Integer, String> {
Context c;
String address;
ListView lv;
ProgressDialog pd;
public Downloader(Context c, String address, ListView lv) {
this.c = c;
this.address = address;
this.lv = lv;
}
//BEFORE JOB STARTS
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Fetch Data");
pd.setMessage("Please Wait");
pd.show();
}
#Override
protected String doInBackground(Void... params) {
String data = downloadData();
return data;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
if(s != null){
Parser p =new Parser(c,s,lv);
p.execute();
}else
{
Toast.makeText(c,"Unable to download data",Toast.LENGTH_SHORT).show();
}
}
private String downloadData(){
//connect and get a stream
InputStream is = null;
String line = null;
try{
URL url = new URL(address);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(con.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
if(br != null){
while((line = br.readLine()) != null)
{
sb.append(line+"\n");
}
}
else
{
return null;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
and my Parser.java
public class Parser extends AsyncTask<Void,Integer,Integer> {
Context c;
ListView lv;
String data;
ArrayList<String> categories = new ArrayList<>();
ProgressDialog pd;
public Parser(Context c, String data, ListView lv) {
this.c = c;
this.data = data;
this.lv = lv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Parser");
pd.setMessage("Please Wait");
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parse();
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer == 1)
{
//ADAPTER
ArrayAdapter<String> adapter = new ArrayAdapter<String>(c, android.R.layout.simple_list_item_1, categories);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}else
{
Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
}
pd.dismiss();
}
//PARSE RECEIVED DATA
private int parse(){
try
{
//ADD TGAT DATA TO JSON ARRAY FIRST
JSONArray ja = new JSONArray(data);
//CREATE JO OBJECT TO HOLD A SINGLE ITEM
JSONObject jo = null;
categories.clear();
//LOOP THROUGH ARRAY
for(int i =0 ; i<ja.length();i++)
{
jo = ja.getJSONObject(i);
//RETRIEVE NAME
String name=jo.getString("cat_name");
//ADD TO ARRAY LIST
categories.add(name);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
I have problem with notifyDataSetChanged,i read some another post but can't help me and i have problem yet, i call that after my listview setadapter but mylist hasn't any change! this is my code, please help me, Thanks
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
// this will post our text data
protected void onPreExecute() {
super.onPreExecute();
// do stuff before posting data
}
#Override
protected String doInBackground(String... strings) {
try {
postTextandGetRespons("http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php");
JSONObject JsonOb = new JSONObject(responseString);
JSONArray messages = JsonOb.getJSONArray("Users");
for ( int i=0; i<= f;i++){
JSONObject c = messages.getJSONObject(i);
firstname = c.getString("firstname");
lastname = c.getString("lastname");
username = c.getString("username");
items.add(new item(firstname,lastname,username));
}
adapter.notifyDataSetChanged();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String responseStr) {
if ( setAdapter == true) {
lv = (ListView) findViewById(R.id.listView_asabani);
adapter = new adapter_common(getBaseContext(), items);
lv.setAdapter(adapter);
setAdapter = false;
}
}
}
Move adapter.notifyDataSetChanged(); to onPostExecute() that's where UI code should run.
I want to add item into listview using async task, so in doinbackgroud it will process and get the data one by one and then display it on listview one by one .
But for my app doinbackground process all the data and then it will display into listview.
public class NewGetContacts extends AsyncTask<String[], Void, Void> {
private static final String TAG_TX = "txid";
private static final String TAG_FEE = "fees";
MyCustomAdapter mAdapter=new MyCustomAdapter();
ListView listViewHandle1 = (ListView) findViewById(R.id.listView2);
#Override
protected Void doInBackground(String[]... params) {
// TODO Auto-generated method stub
int len = params[0].length;
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
// String jsonStr;
mAdapter.addSeparatorItem("Transaction ...");
for(int i=0;i<len ;i++){
String turl = "https://coin/api/tx/"+params[0][i];
try {
String jsonStr1 = sh.makeServiceCall(turl, ServiceHandler.GET);
JSONObject jsonObj2 = new JSONObject(jsonStr1);
txtid = jsonObj2.getString(TAG_TX);
mAdapter.addItem("Transaction ID : "+txtid);
publishProgress();
}catch(Exception e){
Log.d("Exception In TXID -- >",e.getMessage());
}
}
return null;
}
protected void onProgressUpdate(Void... r) {
super.onProgressUpdate(r);
Log.d("Txid 14546465 ","--->");
mAdapter.notifyDataSetChanged();
listViewHandle1.requestLayout();
super.onProgressUpdate(r);
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
listViewHandle1.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
}
Call this in oncreate on your activity/fragment
Class TestActivity extends Activty {
MyCustomAdapter mAdapter ;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mAdapter=new MyCustomAdapter();
ListView listViewHandle1 = (ListView) findViewById(R.id.listView2);
listViewHandle1.setAdapter(mAdapter);
(new NewGetContacts()).execute();
}
}
Then do following in your AsyncTask class
protected Void doInBackground(String[]... params) { //Same as yours
// TODO Auto-generated method stub
int len = params[0].length;
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
// String jsonStr;
mAdapter.addSeparatorItem("Transaction ...");
for(int i=0;i<len ;i++){
String turl = "https://coin/api/tx/"+params[0][i];
try {
String jsonStr1 = sh.makeServiceCall(turl, ServiceHandler.GET);
JSONObject jsonObj2 = new JSONObject(jsonStr1);
txtid = jsonObj2.getString(TAG_TX);
mAdapter.addItem("Transaction ID : "+txtid);
publishProgress();
}catch(Exception e){
Log.d("Exception In TXID -- >",e.getMessage());
}
}
return null;
}
protected void onProgressUpdate(Void... r) {
super.onProgressUpdate(r);
mAdapter.notifyDataSetChanged();
Log.d("Txid 14546465 ","--->");
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Removed set adapter from here
mAdapter.notifyDataSetChanged();
}
I have a listView that can get data from MySql using AsyncTask, but my problem is when i add some buttons and images in the ListView. I added some buttons but i can use it and the image won't display.
here's my code...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
studentList = new ArrayList<HashMap<String, String>>();
new Loadstudent().execute();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), Maindetail.class);
String sidlist = ((TextView) view.findViewById(R.id.tid)).getText().toString();
String namelist = ((TextView) view.findViewById(R.id.sname)).getText().toString();
i.putExtra(TAG_ID, sidlist);
i.putExtra(TAG_NAME, namelist);
startActivity(i);
}
});
}
class Loadstudent extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading students. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_student, "GET", params);
Log.d("ALL student: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if(success == 1) {
student = json.getJSONArray(TAG_STUDENT);
for (int i=0; i<student.length(); i++) {
JSONObject c = student.getJSONObject(i);
sid = c.getString(TAG_ID);
name = c.getString(TAG_NAME);
photo = c.getString(TAG_PHOTO);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, sid);
map.put(TAG_NAME, name);
map.put(TAG_PHOTO, photo);
studentList.add(map);
}
}else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, studentList,
R.layout.list_main, new String[] {
TAG_PHOTO,TAG_ID, TAG_NAME},
new int [] { R.id.imageviewlist, R.id.tid, R.id.sname });
setListAdapter(adapter);
}
});
}
}
I student the lazyadapter from the net, but got a problem combining it to code.
there's any tutorial or link that can solved my problem would be a great help. Thanks in advance.
hey try below approach-
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(getApplicationContext(), Maindetail.class);
HashMap<String, String> data = studentList.get(position);
String sidlist = data.get(TAG_ID);
String namelist = data.get(TAG_NAME);
i.putExtra(TAG_ID, sidlist);
i.putExtra(TAG_NAME, namelist);
startActivity(i);
}
});
You have to create your own adapter for the listview if you want to add extra components in every row layout.
It's not easy, but it's all here coded by me few time ago --> ListView Custom Adapter getView
I hope this helps you!
I have one ListView,I have made a custom adapter for binding data to it,I have made an asynctask in the activity for getting data and display it into the listView,I have two different Urls for the same asyctask ,based on the condition i am using it,Thing is that when i am second time the listView doesn't remove the previous values.
main.java
public class MyMessagesActivity extends Activity {
private ProgressDialog pDialog;
JSONArray msgArry;
private MessageAdapter msgContent;
ArrayList<HashMap<String, String>> msgList;
ListView lv;
JSONArray msgs = null;
String pro_id, pro_name, pro_img, pro_unit;
TextView tv_switch;
public boolean flag = false;
Header header;
Menu menu;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_messgaes);
lv = (ListView) findViewById(R.id.list);
tv_switch = (TextView) findViewById(R.id.tv_switch);
header = (Header) findViewById(R.id.header_msg);
menu = (Menu) findViewById(R.id.menu_msg);
menu.setSelectedTab(3);
header.title.setText("Messages");
msgList = new ArrayList<HashMap<String, String>>();
// url = "?customer_id=" + Pref.getValue(MyMessagesActivity.this,
// Const.PREF_CUSTOMER_ID, "") + "&group_id=2";
tv_switch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (flag) {
tv_switch.setText("Switch to supplier");
new GetMessages().execute();
flag = false;
} else {
tv_switch.setText("Switch to buyer");
new GetMessages().execute();
flag = true;
}
}
});
// AsyncTAsk for Wholesale Product List...!!!
new GetMessages().execute();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
// in = new Intent(getApplicationContext(),
// ProductDetailActivity.class);
/*
* pro_name = ((TextView)
* view.findViewById(R.id.product_label)).getText().toString();
*
* // getting ProductId from the tag...
*
* pro_id = msgList.get(position).get(Const.TAG_PRODUCT_ID);
* pro_name = msgList.get(position).get(Const.TAG_PRODUCT_NAME);
* pro_img = msgList.get(position).get(Const.TAG_PRODUCT_IMG);
* System.out.println(
* ":::::::::::::::;;THE INTENT FOR THE PRODUCUT DETIALS ACTIVITY================="
* + pro_name); Toast.makeText(MyMessagesActivity.this,
* pro_name, Toast.LENGTH_SHORT).show();
*/
// startActivity(in);
}
});
}
private class GetMessages extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MyMessagesActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
String query = Const.API_MESSAGES;
if (flag) {
url = "?customer_id=" + Pref.getValue(MyMessagesActivity.this, Const.PREF_CUSTOMER_ID, "") + "&group_id=1";
} else {
url = "?customer_id=" + Pref.getValue(MyMessagesActivity.this, Const.PREF_CUSTOMER_ID, "") + "&group_id=2";
}
url = url.replace(" ", "%20");
url = query + url;
System.out.println(":::::::::::::My MESSGES URL::::::::::::::" + url);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
msgArry = new JSONArray(jsonStr);
if (msgArry != null && msgArry.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + msgArry.length());
for (int i = 0; i < msgArry.length(); i++) {
JSONObject c = msgArry.getJSONObject(i);
String custID = c.getString(Const.TAG_CUSTOMER_ID);
String custName = c.getString(Const.TAG_CUSTOMER_NAME);
String proID = c.getString(Const.TAG_PRODUCT_ID);
String email = c.getString(Const.TAG_CUSTOMER_EMAIL);
String photo = Const.API_HOST + "/" + c.getString(Const.TAG_PHOTO);
String subject = c.getString(Const.TAG_SUBJECT);
String msg_read = c.getString(Const.TAG_MESSAGE_READ);
HashMap<String, String> message = new HashMap<String, String>();
message.put(Const.TAG_CAT_ID, custID);
message.put(Const.TAG_CUSTOMER_NAME, custName);
message.put(Const.TAG_PRODUCT_ID, proID);
message.put(Const.TAG_CUSTOMER_EMAIL, email);
message.put(Const.TAG_PHOTO, photo);
message.put(Const.TAG_SUBJECT, subject);
message.put(Const.TAG_MESSAGE_READ, msg_read);
msgList.add(message);
}
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Utils.showCustomeAlertValidation(MyMessagesActivity.this, "No messgaes found", "yehki", "Ok");
}
});
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
msgContent.notifyDataSetChanged();
lv.setAdapter(msgContent);
}
}
}
Please help me for it,thank you eve-one
Try to remove the old records from your HashMap arraylist as below to remove all the data from arraylist.
After binding the data into ListView just clear your arraylist as below:
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
msgContent.notifyDataSetChanged();
lv.setAdapter(msgContent);
msgList.clear();
}
just clear your list
add mgList.clear(); in protected void onPreExecute()..
Put these lines in OnCreate() method itself,
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
lv.setAdapter(msgContent);
Use this line in onPostExecute() of the AsynTask class,
msgContent.notifyDataSetChanged();
If this doesn't work try to add static keyword before msglist variable.
In your doInBackground() add below line before starting for loop:
msgList.clear();
You need to call msgList.clear(); before add data in to msgList arrayList. After that in onPostExecute() method just check condition while set adapter in to listview,
try {
if (msgList!= null
&& msgList.size() > 0) {
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
lv.setAdapter(msgContent);
msgContent.notifyDataSetChanged();
} else {
Toast.makeText(YourActivityName.this,
"No Data connection", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
Clearing the msgList is not worked for me. And use
msgList = new ArrayList>();
in doInBackground() before you adding the new content to the list. And just an info, there is no need to call notifyDataSetChanged() when you set a new instance of the adapter to a listview(And there is no problem if you called the notifyDataSetChanged).
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
lv.setAdapter(msgContent);