gpt4 book ai didi

android - 如何在 asynctask android 之后刷新 ListView

转载 作者:行者123 更新时间:2023-11-29 21:05:26 25 4
gpt4 key购买 nike

我有一个像 Facebook 一样的页面时间线(有 EditText 和 Button),它有 2 个异步任务。第一个用于向远程服务器发送参数,第二个用于从 URL 加载数据 json。实际上第一次,程序将异步加载 ListView 上的 JSON,然后如果我想在单击按钮后更新状态,那么它将插入到远程服务器上的表中。他们都成功地工作。但我有一个小问题:点击按钮(更新状态)后我想刷新我的 ListView 。我在事件单击按钮上添加了代码,然后添加了 onPostExecute(类 TheTask)。发送参数后,listview 不再重新加载内容。有人可以帮我解决这个问题吗?

我的源代码:

public class Timeline extends Activity {
private static String BaseUrl="";
private String status;
final int PROGRESS_DIALOG=1;
private ProgressBar pb;

ViewConnection connection;

ArrayList<URLPostClass> timelinelist=new ArrayList<URLPostClass>();
ArrayList<URLPostClass> arrtimeline=new ArrayList<URLPostClass>();
//ArrayList<String> arritemcategory;

ListView listview;
//ListViewAdapter ListViewAdapter;

@Override
protected Dialog onCreateDialog(int id) {
switch(id)
{
case PROGRESS_DIALOG:
ProgressDialog progress =new ProgressDialog(this);
progress.setMessage("Loading");
progress.setTitle("Memuat status");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setProgress(0);
progress.setMax(100);
return progress;
}
return super.onCreateDialog(id);
}

private class GetTimelineAyncTask extends AsyncTask<Hashtable<String,String>,Void,String> {
@Override
protected void onPreExecute() {
showDialog(PROGRESS_DIALOG);
super.onPreExecute();
}
@Override
protected String doInBackground(Hashtable<String, String>... params)
{
// TODO Auto-generated method stub
Hashtable ht=params[0];

String json=HelperHttp.getJSONResponseFromURL(BaseUrl, ht);
if(json!=null) {
parseJsonString(timelinelist,json);
}else{
return "No internet access";
}
return json;
}

protected void parseJsonString(ArrayList<URLPostClass> timelinelistjs,String json){
try {
JSONObject jsonObj = new JSONObject(json);
JSONArray array = jsonObj.getJSONArray("listtimeline");

URLPostClass.setlength(array.length());

for (int i=0;i<array.length();i++){
JSONObject js=array.getJSONObject(i);

URLPostClass timeline=new URLPostClass(js.getString("IdTimeline"),
js.getString("NamaSales"),
js.getString("JenisStatus"),
js.getString("Remark"),
js.getString("TgglInsert"),
js.getString("Path"));
timelinelistjs.add(timeline);
}
}catch (JSONException e) {
e.printStackTrace();
}
}

@Override
protected void onPostExecute(String result){
if(result=="SUCCESS")
{
}else{
DecimalFormat formatter = new DecimalFormat("#,###,###");

JSONObject jObject = null;
Context mContext = null;
try {
jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("listtimeline");

for (int i=0; i < jArray.length(); i++)
{
JSONObject oneObject=jArray.getJSONObject(i);
URLPostClass timeline=new URLPostClass(oneObject.getString("IdTimeline"),
oneObject.getString("NamaSales"),
oneObject.getString("JenisStatus"),
oneObject.getString("Remark"),
oneObject.getString("TgglInsert"),
oneObject.getString("Path"));
arrtimeline.add(timeline);
}
listview = (ListView) findViewById(R.id.listtimeline);
listview.setAdapter(new ListViewTimelineAdapter(getBaseContext(), arrtimeline));
}catch (JSONException e) {
e.printStackTrace();
}
}
removeDialog(PROGRESS_DIALOG);
super.onPostExecute(result);
}
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeline);
Global.Timeline=this;

final RadioButton rbtnlisting=(RadioButton)findViewById(R.id.rbtnlisting);
final RadioButton rbtnclosing=(RadioButton)findViewById(R.id.rbtnclosing);
final RadioButton rbtnprospek=(RadioButton)findViewById(R.id.rbtnprospek);
final EditText edtstatus=(EditText)findViewById(R.id.edtstatus);
Button btnpost=(Button)findViewById(R.id.btnpost);

edtstatus.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
btnpost.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
rbtnlisting.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
rbtnclosing.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
rbtnprospek.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));

listview = (ListView) findViewById(R.id.listtimeline);

pb=(ProgressBar)findViewById(R.id.progressBar1);
pb.setVisibility(View.GONE);

connection = new ViewConnection(getBaseContext());
if (connection.isConnectingToInternet())
{
btnpost.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
if (edtstatus.getText().length()>5) {
pb.setVisibility(View.VISIBLE);
TheTask async=new TheTask();
async.execute("ccc");
}else {
Toast.makeText(getBaseContext(), "Your status is too short", Toast.LENGTH_LONG).show();
}
}
});

BaseUrl="http://xxx.xxx.xxx.xxx/dummy/gettimeline.php";
executeAsyncTask();
}else {

// Internet connection is not present
LayoutInflater li = LayoutInflater.from(Timeline.this);
final View inputdialogcustom = li.inflate(R.layout.activity_confirm_connection, null);
AlertDialog.Builder alert = new AlertDialog.Builder(Timeline.this);
alert.setView(inputdialogcustom);

alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
alert.show();
}

}
class TheTask extends AsyncTask<String, Integer, Double>
{
@Override
protected Double doInBackground(String... params) {
postData(params[0]);
return null;
}

protected void onPostExecute(Double result) {
// TODO Auto-generated method stub
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Status telah diposting !", Toast.LENGTH_LONG).show();

BaseUrl="http://xxx.xxx.xxx.xxx/dummy/gettimeline.php"; // I PUT ON HERE
executeAsyncTask();
}
protected void onProgressUpdate(Integer... progress){
pb.setProgress(progress[0]);
}

public void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
RadioButton rbtnlisting=(RadioButton)findViewById(R.id.rbtnlisting);
RadioButton rbtnclosing=(RadioButton)findViewById(R.id.rbtnclosing);
RadioButton rbtnprospek=(RadioButton)findViewById(R.id.rbtnprospek);
EditText edtstatus=(EditText)findViewById(R.id.edtstatus);

if (edtstatus.getText().length()>5) {
RadioGroup radiotipe = (RadioGroup) findViewById(R.id.radiotipe);
int selectedId = radiotipe.getCheckedRadioButtonId();

RadioButton rbtnselected=(RadioButton) findViewById(selectedId);
status=rbtnselected.getText().toString();

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxx.xxx.xxx.xxx/dummy/insert.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("idsales",OtherClass.getIdSales().toString()));
nameValuePairs.add(new BasicNameValuePair("jenis", status));
nameValuePairs.add(new BasicNameValuePair("remark", edtstatus.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("path", "coba coba"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
HttpResponse response=httpclient.execute(httppost);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
// TODO Auto-generated catch block
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

}else {
Toast.makeText(getBaseContext(), "Your status is too short", Toast.LENGTH_LONG).show();
}
}
}
private void executeAsyncTask(){
Hashtable<String,String> ht=new Hashtable<String,String>();
GetTimelineAyncTask async=new GetTimelineAyncTask();
Hashtable[] ht_array={ht};
async.execute(ht_array);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.tab_sport, menu);
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.menutimeline, menu);

return super.onCreateOptionsMenu(menu);
}

@SuppressLint("NewApi")
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.menulogout:
//Toast.makeText(getBaseContext(), "test", Toast.LENGTH_LONG).show();

//View view = item.getActionView();
//final EditText edtsearchitem=(EditText)view.findViewById(R.id.edtsearchitem);
OtherClass.setIdSales("");
Global.Timeline.finish();

Intent MyIntentDetailItem=new Intent(getBaseContext(), MainActivity.class);
startActivity(MyIntentDetailItem);

return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

最佳答案

在这里您必须创建全局适配器并使用适配器调用 notifydatasetchanged()

全局声明

ListViewTimelineAdapter 适配器=null;

并替换

listview = (ListView) findViewById(R.id.listtimeline); 
listview.setAdapter(new ListViewTimelineAdapter(getBaseContext(), arrtimeline));

编码

listview = (ListView) findViewById(R.id.listtimeline); 
adapter=new ListViewTimelineAdapter(getBaseContext(), arrtimeline);
listview.setAdapter(adapter);
adapter.NotifyDatasetChanged();

就是这样......当你想刷新列表时只需写

adapter.NotifyDatasetChanged();

并重新加载 ListView ...

关于android - 如何在 asynctask android 之后刷新 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24737311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com