我有一个调用Java类(JsonTaskPost)的活动(LoginActivity)。我想在用户单击按钮时显示一个进度栏,而java类同时执行其任务。我想代码必须运行得太快,进度条才能被看到。那么如何在20秒内增加进度条的可见性呢?还是逻辑错了?
LoginActivity.java
package com.example.mymobileforumbrowser2;
import android.app.ProgressDialog;
import android.content.Intent;
import android.icu.util.TimeUnit;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import static com.example.mymobileforumbrowser2.MainActivity.LOGIN_ACTIVITY;
import static com.example.mymobileforumbrowser2.MainActivity.mSharedEditor;
import static com.example.mymobileforumbrowser2.MainActivity.makeToast;
import static com.example.mymobileforumbrowser2.MainActivity.serverUrl;
public class LoginActivity extends AppCompatActivity {
public static TextView serverMessageTxv;
EditText usernameEditTxv,passwordEditTxv;
Button loginButton;
ProgressDialog progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
serverMessageTxv = (TextView)findViewById(R.id.server_message);
usernameEditTxv = (EditText)findViewById(R.id.username_edittextview);
passwordEditTxv = (EditText)findViewById(R.id.password_edittextview);
loginButton = (Button)findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
progress = ProgressDialog.show(LoginActivity.this, "LOG IN",
"Logging Please Wait ...", true);
new Thread(new Runnable() { // open new thread gia background processing
@Override
public void run() {
String url = serverUrl + "login.php";
//Log.d("EXEC_JSON","CALL JSON");
new JsonTaskPost().execute(url,
usernameEditTxv.getText().toString(),
passwordEditTxv.getText().toString(),
LOGIN_ACTIVITY);
runOnUiThread(new Runnable() {
@Override
public void run() {
progress.dismiss();
}
});
}
}).start();
/*
String url = serverUrl + "login.php";
new JsonTaskPost().execute(url,
usernameEditTxv.getText().toString(),
passwordEditTxv.getText().toString(),
LOGIN_ACTIVITY);
*/
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem topicItem = menu.findItem(R.id.new_topic);
topicItem.setVisible(false);
MenuItem postItem = menu.findItem(R.id.new_post);
postItem.setVisible(false);
//MenuItem mapItem = menu.findItem(R.id.map);
//mapItem.setVisible(false);
MenuItem loginItem = menu.findItem(R.id.login);
loginItem.setVisible(false);
invalidateOptionsMenu();
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
Intent intent;
// Handle item selection
switch (item.getItemId()) {
case R.id.preferences:
intent = new Intent(this, PreferencesActivity.class);
startActivity(intent);
return true;
case R.id.logout:
if(mSharedEditor!= null)
{
mSharedEditor.putString("Username", "");
mSharedEditor.putBoolean("LoggedIn", false);
mSharedEditor.commit();
makeToast(this, "Successfully logged out");
}
return true;
case R.id.register:
intent = new Intent(this, RegisterActivity.class);
startActivity(intent);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
JsonTaskPost.java
package com.example.mymobileforumbrowser2;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONObject;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import static com.example.mymobileforumbrowser2.LoginActivity.serverMessageTxv;
import static com.example.mymobileforumbrowser2.MainActivity.LOGIN_ACTIVITY;
//import static com.example.mymobileforumbrowser2.MainActivity.MAPS_ACTIVITY;
import static com.example.mymobileforumbrowser2.MainActivity.NEWPOST_ACTIVITY;
import static com.example.mymobileforumbrowser2.MainActivity.NEWTOPIC_ACTIVITY;
import static com.example.mymobileforumbrowser2.MainActivity.POSTS_ACTIVITY;
import static com.example.mymobileforumbrowser2.MainActivity.REGISTER_ACTIVITY;
import static com.example.mymobileforumbrowser2.MainActivity.TOPICS_ACTIVITY;
import static com.example.mymobileforumbrowser2.MainActivity.mSharedEditor;
import static com.example.mymobileforumbrowser2.MainActivity.mSharedPrefs;
import static com.example.mymobileforumbrowser2.MainActivity.removeHtmlChars;
import static com.example.mymobileforumbrowser2.MainActivity.stringToListView;
import static com.example.mymobileforumbrowser2.PostsActivity.adapterPosts;
import static com.example.mymobileforumbrowser2.PostsActivity.postsListItems;
import static com.example.mymobileforumbrowser2.RegisterActivity.registerServerMessageTxv;
import static com.example.mymobileforumbrowser2.TopicsActivity.adapterTopics;
import static com.example.mymobileforumbrowser2.TopicsActivity.topicsListItems;
//post-get class
// fetches topics / posts an ginetai call apo TopicsActivity / PostsActivity
public class JsonTaskPost extends AsyncTask<String, String, String>
{
String message = null;
String usernameSharedPrefs;
String callingActivity;
JSONObject jsonObject;
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
OutputStream outStream = null;
callingActivity = params[3]; // orizetai apo caller
Log.d("Calling Activity",callingActivity);
usernameSharedPrefs = params[1]; //string of username if login called, else forum / topic name depending on caller activity
Log.d("USERNAME",usernameSharedPrefs);
try {
URL url = new URL(params[0]); // callers url adress, eg http:localhost/phpbb/fetch_forums.php
Log.d("CALLERS URL",params[0]);
jsonObject = new JSONObject();
message = paramsTojson(params).toString(); // metatrepei periexomena Json array se string , {"key:","value"}
Log.d("MESSAGE",message);
connection = (HttpURLConnection) url.openConnection(); //open connection to phpbb database
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setFixedLengthStreamingMode(message.getBytes().length);
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
outStream = new BufferedOutputStream(connection.getOutputStream());
outStream.write(message.getBytes());
outStream.close();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally
{
if (connection != null){
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result)
{
if(result!=null)
{
if(callingActivity.equals(TOPICS_ACTIVITY))
{
stringToListView(result,topicsListItems);
adapterTopics.notifyDataSetChanged(); // prosarmogh periexomenwn listview toy topics activity sta nea periexomena
}
else if(callingActivity.equals(POSTS_ACTIVITY))
{
stringToListView(result,postsListItems);
adapterPosts.notifyDataSetChanged();
}
else if(callingActivity.equals(REGISTER_ACTIVITY))
{
result = removeHtmlChars(result);
if(result.contains("You are registered"))
registerServerMessageTxv.setText(result);
}
else if(callingActivity.equals(LOGIN_ACTIVITY))
{
result = removeHtmlChars(result);
serverMessageTxv.setText(result);
mSharedEditor = mSharedPrefs.edit();
if (result.contains("You are logged in"))
{
mSharedEditor.putString("Username",usernameSharedPrefs);
mSharedEditor.putBoolean("LoggedIn",true);
mSharedEditor.commit();
}
else // LOGOUT / no user logged in
{
mSharedEditor.putString("Username","");
mSharedEditor.putBoolean("LoggedIn",false);
mSharedEditor.commit();
}
}
}
super.onPostExecute(result);
}
protected JSONObject paramsTojson(String... params)
{
try
{
if (params[3].equals(LOGIN_ACTIVITY)) {
jsonObject.put("username", params[1]);
jsonObject.put("password", params[2]);
} else if (params[3].equals(TOPICS_ACTIVITY)) {
jsonObject.put("forum_name", params[1]);
jsonObject.put("number_of_topics", params[2]);
} else if (params[3].equals(POSTS_ACTIVITY)) {
jsonObject.put("topic_name", params[1]);
jsonObject.put("number_of_posts", params[2]);
} else if (params[3].equals(REGISTER_ACTIVITY)) {
jsonObject.put("username", params[1]);
jsonObject.put("password", params[2]);
jsonObject.put("email", params[4]);
} else if (params[3].equals(NEWTOPIC_ACTIVITY)) {
jsonObject.put("forum_name", params[1]);
jsonObject.put("topic_title", params[2]);
jsonObject.put("username", params[4]);
} else if (params[3].equals(NEWPOST_ACTIVITY)) {
jsonObject.put("topic_name", params[1]);
jsonObject.put("forum_name", params[4]);
jsonObject.put("username", params[5]);
jsonObject.put("post_text", params[2]);
}
/*
else if (params[3].equals(MAPS_ACTIVITY)) {
jsonObject.put("username", params[1]);
jsonObject.put("timestamp", params[2]);
jsonObject.put("longitude", params[4]);
jsonObject.put("latitude", params[5]);
}
*/
}
catch (org.json.JSONException e)
{
e.printStackTrace();
}
return jsonObject;
}
}
最佳答案
您的代码是错误的,这就是为什么它正在发生。呼叫progress.dismiss();
之后,您正在呼叫AsyncTask
。这就是progressbar
在任务完成之前被解雇的原因。
您已经在使用JsonTaskPost(AsyncTask)
,因此无需在此处使用单独的线程。您需要从progress.dismiss();
的onPostExecute
调用JsonTaskPost
,因为此方法是任务完成的地方。因此,为此您可以创建回调以完成任务,或者将progressBar
实例传递给JsonTaskPost
或直接在活动本身中使用AsyncTask
。