我想在等待服务器响应时显示一个进度Dialog 。
我班的Jogar Acticity(我的应用程序是一个测验游戏)做以下工作:
1- 初始化变量
2. 核实是否属于第一个问题(PrimeiraPergunta)
2.1- 如果回答第一个问题, 请拨打用户功能. getJogar () 。 此函数将创建带有参数的列表, 并发送到 JSONParser 类。 JSONParser 提出 http 请求, 并用数据返回 JSONArray 。
2.2 - 如果这不是第一个问题,请从意图外增加中检索实际问题。
3- 尝试将 JSONArray 解析为字符串。 如果用户已经回答了实际分类中的所有问题, 这将返回例外( JSONArray 将无效), 这样它可以显示一个对话框, 请用户选择另一个分类 。
4- 将所有数据(问答选项)放入屏幕,等待用户互动。
5- 当用户选择一个答案时, 它会称为 UsepherFunctions.gerResposga () 。 此时, 它会在更新数据库( 提示、 回答问题等) 后返回一个状态信息( 正确、 错误、 错误等) 。 它还会检索下一个问题 。
6 - 显示一个包含问题信息的对话框和一个确定按钮, 当按下该按钮时会重新启动活动。 下一个问题作为意向. putExtra () 传递, 而 piniraPergunta (第一个问题? ) 被设置为虚假 。
*UserFunctions and JSONParser are not activities, so I can t use ProgressDialog inside them, as long as I can t retrieve application s context. *JSONParser is used by other classes, so I prefer not to changing it *I m looking for another solution than rewriting everithing in JogarActivity (that will make necessary to change other classes too).
我首先在Jogar Actituality下面贴过Jogar Acticalivity,没有变化。然后,我试图添加一个 Asynctask 来显示ProgressDialog, 但是它只是没有出现在屏幕上( AsyncTask.get () 用来让Jogar Acticity 等待 Asynctask 的结果 ) 。 Finnaly,我粘贴了另一个 Asynctask 工作正常的班级( Register Acticity ) 。
我想AsyncTashsk可能不是最好的方法,但我只是想尽快让它生效。这不是我的代码(注册活动除外 ) 。 应用程序工作后, 我将优化它 :
Jogar activity. 贾瓦瓦
public class JogarActivity extends Activity {
private static final String TAG_RESPOSTA = "resposta";
private static final String TAG_ID = "idt";
private static final String TAG_PRIMEIRAPERGUNTA = "primeiraPergunta";
private static final String TAG_JSON = "json";
private Integer idPergunta;
private String pergunta;
private String respostaRecebe; //Texto da resposta que o usuário escolheu
private String respostaConfere;
private String resposta;
private String idCategoria;
private String respostaCorreta;
private String[] arrayRespostas = new String[5];
private boolean primeiraPergunta;
private JSONArray json;
private JSONArray jsonResposta;
String idUser;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jogar_layout);
Intent in = getIntent();
String url = this.getString(R.string.urlSite);
ArrayList<HashMap<String, String>> respostaList = new ArrayList<HashMap<String, String>>();
String idt = in.getStringExtra(TAG_ID);
primeiraPergunta = in.getBooleanExtra(TAG_PRIMEIRAPERGUNTA, true);
TextView insertPergunta = (TextView) findViewById(R.id.insertPergunta);
ListView insertRespostas = (ListView) findViewById(R.id.listResposta);
SharedPreferences settings = getSharedPreferences("PREFS_LOGIN", MODE_PRIVATE);
Integer idUsuario = settings.getInt("idUsuario", 0);
idUser = idUsuario.toString();
if (primeiraPergunta){
UserFunctions userFunction = new UserFunctions();
json = userFunction.getJogar(idt, idUser);
时 时else{
try {
json = new JSONArray(in.getStringExtra(TAG_JSON));
json = json.getJSONArray(2);
时 时 catch (JSONException e) {
e.printStackTrace();
时 时
时 时
try{
@SuppressWarnings("unused")
String s = json.toString(); // Se o usuário já respondeu todas as perguntas da categoria, retorna uma Exception
try {
idPergunta = json.getInt(0);
pergunta = json.getString(1);
for (int i=2; i<7 ; i++){
resposta = json.getString(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_RESPOSTA, resposta);
respostaList.add(map);
arrayRespostas[i-2] = resposta;
时 时
respostaCorreta = json.getString(7);
respostaConfere = arrayRespostas[Integer.parseInt(respostaCorreta)-1];
idCategoria = json.getString(11);
时 时 catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
时 时
insertPergunta.setText(pergunta);
ListAdapter adapter = new SimpleAdapter(this, respostaList,
R.layout.resposta_data,
new String[] { TAG_RESPOSTA 时 时, new int[] {
R.id.insertResposta 时 时);
insertRespostas.setAdapter(adapter);
// selecting single ListView item
ListView lv = insertRespostas;
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Integer pos = position + 1;
String respostaEscolhida = pos.toString();
String pergunta = idPergunta.toString();
UserFunctions userFunction = new UserFunctions();
final JSONArray jsonResposta = userFunction.getResposta(pergunta, idUser , respostaEscolhida, idCategoria);
respostaRecebe = arrayRespostas[position];
String mensagem = "";
try {
mensagem = jsonResposta.getString(1);
时 时 catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
时 时
final String jrString = jsonResposta.toString();
AlertDialog alertDialog = new AlertDialog.Builder(
JogarActivity.this).create();
if (respostaCorreta.equals(pos.toString())){
alertDialog.setTitle("PARABÉNS");
alertDialog.setMessage("Resposta correta: "+respostaRecebe+"
"+mensagem);
时 时
else{
alertDialog.setTitle("VOCÊ ERROU");
alertDialog.setMessage("Sua resposta: "+respostaRecebe+"
Resposta correta: "+respostaConfere+"
"+mensagem);
时 时
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(),JogarActivity.class);
//in.putExtra(TAG_NAME, name);
i.putExtra(TAG_ID, idCategoria);
i.putExtra(TAG_PRIMEIRAPERGUNTA, false);
i.putExtra(TAG_JSON, jrString);
startActivity(i);
finish();
时 时
时 时);
alertDialog.show();
时 时
时 时);
时 时catch (Exception e){
AlertDialog sem_perguntas = new AlertDialog.Builder(
JogarActivity.this).create();
sem_perguntas.setTitle("PARABÉNS");
sem_perguntas.setMessage("Você já respondeu todas as perguntas desta categoria!");
sem_perguntas.setButton("VOLTAR", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(),CategoriasJogarActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
finish();
时 时
时 时);
sem_perguntas.show();
//finish();
时 时
//finish();
时 时
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu_jogar, menu);
return true;
时 时
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_pularPergunta:
Intent i = new Intent(getApplicationContext(),JogarActivity.class);
startActivity(i);
finish();
Toast.makeText(JogarActivity.this, "Pergunta Pulada", Toast.LENGTH_SHORT).show();
return true;
时 时
return false;
时 时
时 时
Jogar Actionivity with AsyncTask (进步迪亚洛格没有出现)
public class JogarActivity extends Activity {
private static final String TAG_RESPOSTA = "resposta";
private static final String TAG_ID = "idt";
private static final String TAG_PRIMEIRAPERGUNTA = "primeiraPergunta";
private static final String TAG_JSON = "json";
private Integer idPergunta;
private String pergunta;
private String respostaRecebe; //Texto da resposta que o usuário escolheu
private String respostaConfere;
private String resposta;
private String idCategoria;
private String respostaCorreta;
private String[] arrayRespostas = new String[5];
private boolean primeiraPergunta;
private JSONArray json;
private JSONArray jsonResposta;
ProgressDialog pDialog;
Context ctx = this;
String idUser;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jogar_layout);
Intent in = getIntent();
String url = this.getString(R.string.urlSite);
ArrayList<HashMap<String, String>> respostaList = new ArrayList<HashMap<String, String>>();
String idt = in.getStringExtra(TAG_ID);
primeiraPergunta = in.getBooleanExtra(TAG_PRIMEIRAPERGUNTA, true);
TextView insertPergunta = (TextView) findViewById(R.id.insertPergunta);
ListView insertRespostas = (ListView) findViewById(R.id.listResposta);
SharedPreferences settings = getSharedPreferences("PREFS_LOGIN", MODE_PRIVATE);
Integer idUsuario = settings.getInt("idUsuario", 0);
idUser = idUsuario.toString();
if (primeiraPergunta){
//UserFunctions userFunction = new UserFunctions();
//json = userFunction.getJogar(idt, idUser);
AsyncTask jogar = new Jogar().execute("url", "http://www.qranio.com/mobile/perguntas.php", "categoria", idt, "idUsuario", idUser);
try {
json = (JSONArray) jogar.get();
时 时 catch (InterruptedException e) {
e.printStackTrace();
时 时 catch (ExecutionException e) {
e.printStackTrace();
时 时
时 时else{
try {
json = new JSONArray(in.getStringExtra(TAG_JSON));
json = json.getJSONArray(2);
时 时 catch (JSONException e) {
e.printStackTrace();
时 时
时 时
try{
@SuppressWarnings("unused")
String s = json.toString(); // Se o usuário já respondeu todas as perguntas da categoria, retorna uma Exception
try {
idPergunta = json.getInt(0);
pergunta = json.getString(1);
for (int i=2; i<7 ; i++){
resposta = json.getString(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_RESPOSTA, resposta);
respostaList.add(map);
arrayRespostas[i-2] = resposta;
时 时
respostaCorreta = json.getString(7);
respostaConfere = arrayRespostas[Integer.parseInt(respostaCorreta)-1];
idCategoria = json.getString(11);
时 时 catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
时 时
insertPergunta.setText(pergunta);
ListAdapter adapter = new SimpleAdapter(this, respostaList,
R.layout.resposta_data,
new String[] { TAG_RESPOSTA 时 时, new int[] {
R.id.insertResposta 时 时);
insertRespostas.setAdapter(adapter);
// selecting single ListView item
ListView lv = insertRespostas;
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Integer pos = position + 1;
String respostaEscolhida = pos.toString();
String pergunta = idPergunta.toString();
//UserFunctions userFunction = new UserFunctions();
//final JSONArray jsonResposta = userFunction.getResposta(pergunta, idUser , respostaEscolhida, idCategoria);
AsyncTask jogar = new Jogar().execute("url", "http://www.qranio.com/mobile/resposta.php", "id_pergunta", pergunta, "id_usuario", idUser, "resposta", respostaEscolhida, "categoria", idCategoria);
try {
jsonResposta = (JSONArray) jogar.get();
时 时 catch (InterruptedException e1) {
e1.printStackTrace();
时 时 catch (ExecutionException e1) {
e1.printStackTrace();
时 时
respostaRecebe = arrayRespostas[position];
String mensagem = "";
try {
mensagem = jsonResposta.getString(1);
时 时 catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
时 时
final String jrString = jsonResposta.toString();
AlertDialog alertDialog = new AlertDialog.Builder(
JogarActivity.this).create();
if (respostaCorreta.equals(pos.toString())){
alertDialog.setTitle("PARABÉNS");
alertDialog.setMessage("Resposta correta: "+respostaRecebe+"
"+mensagem);
时 时
else{
alertDialog.setTitle("VOCÊ ERROU");
alertDialog.setMessage("Sua resposta: "+respostaRecebe+"
Resposta correta: "+respostaConfere+"
"+mensagem);
时 时
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(),JogarActivity.class);
//in.putExtra(TAG_NAME, name);
i.putExtra(TAG_ID, idCategoria);
i.putExtra(TAG_PRIMEIRAPERGUNTA, false);
i.putExtra(TAG_JSON, jrString);
startActivity(i);
finish();
时 时
时 时);
alertDialog.show();
时 时
时 时);
时 时catch (Exception e){
AlertDialog sem_perguntas = new AlertDialog.Builder(
JogarActivity.this).create();
sem_perguntas.setTitle("PARABÉNS");
sem_perguntas.setMessage("Você já respondeu todas as perguntas desta categoria!");
sem_perguntas.setButton("VOLTAR", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(),CategoriasJogarActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
finish();
时 时
时 时);
sem_perguntas.show();
//finish();
时 时
//finish();
时 时
/*public void colocaResposta (int i, JSONArray json, ArrayList respostaList) throws JSONException{
resposta = json.getString(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_RESPOSTA, resposta);
respostaList.add(map);
时 时*/
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu_jogar, menu);
return true;
时 时
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_pularPergunta:
Intent i = new Intent(getApplicationContext(),JogarActivity.class);
startActivity(i);
finish();
Toast.makeText(JogarActivity.this, "Pergunta Pulada", Toast.LENGTH_SHORT).show();
return true;
时 时
return false;
时 时
class Jogar extends AsyncTask<String, Void, JSONArray>{
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ctx);
pDialog.setMessage("Aguarde...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
时 时
@Override
protected JSONArray doInBackground(String... values) {
String url = values[1];
int count = values.length;
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (int i=2; i<count; i++){
params.add(new BasicNameValuePair(values[i], values[i+1]));
i++;
时 时
JSONParser jsonParser = new JSONParser();
JSONArray json = jsonParser.getJSONFromUrl(url, params);
return json;
时 时
protected void onPostExecute(JSONArray result) {
// dismiss the dialog once done
pDialog.dismiss();
时 时
时 时
时 时
注册活动(工作罚款)
public class RegisterActivity extends Activity{
EditText reg_fullname;
EditText reg_email;
EditText reg_login;
EditText reg_password;
EditText reg_password2;
Spinner reg_country;
Spinner reg_genre;
EditText reg_birthday;
EditText reg_promocode;
Button btnRegister;
Context ctx = this;
ProgressDialog pDialog;
JSONArray json;
String status;
String msg;
String fullname;
String email;
String login;
String password;
String password2;
String country;
String genre;
String birthday;
String promocode;
boolean finishActivity = false;
/**
* @see android.app.Activity#onCreate(Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
TextView loginScreen = (TextView) findViewById(R.id.link_to_login);
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Closing registration screen
// Switching to Login Screen/closing register screen
finish();
时 时
时 时);
reg_fullname = (EditText) findViewById(R.id.reg_fullname);
reg_email = (EditText) findViewById(R.id.reg_email);
reg_login = (EditText) findViewById(R.id.reg_login);
reg_password = (EditText) findViewById(R.id.reg_password);
reg_password2 = (EditText) findViewById(R.id.reg_password2); //confirmação de senha
reg_country = (Spinner) findViewById(R.id.reg_country);
reg_genre = (Spinner) findViewById(R.id.reg_genre);
reg_birthday = (EditText) findViewById(R.id.reg_birthday);
reg_promocode = (EditText) findViewById(R.id.reg_promocode);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fullname = reg_fullname.getText().toString();
email = reg_email.getText().toString();
login = reg_login.getText().toString();
password = reg_password.getText().toString();
password2 = reg_password2.getText().toString();
country = reg_country.getSelectedItem().toString();
genre = reg_genre.getSelectedItem().toString();
birthday = reg_birthday.getText().toString();
promocode = reg_promocode.getText().toString();
boolean validation = true;
String message = "Campo de preencimento obrigatório";
if(fullname.equalsIgnoreCase("")){
reg_fullname.setError(message);
validation = false;
时 时
if(email.equalsIgnoreCase("")){
reg_email.setError(message);
validation = false;
时 时
if(!email.matches(".*@.*")){
reg_email.setError("O endereço de email não é válido");
validation = false;
时 时
if(login.equalsIgnoreCase("")){
reg_login.setError(message);
validation = false;
时 时
if(password.equalsIgnoreCase("")){
reg_password.setError(message);
validation = false;
时 时
if(password2.equalsIgnoreCase("")){
reg_password2.setError(message);
validation = false;
时 时
if(!password.equals(password2)){
reg_password2.setError("A confirmação de senha não confere");
validation = false;
时 时
if(birthday.equalsIgnoreCase("")){
reg_birthday.setError(message);
validation = false;
时 时
SimpleDateFormat bd = new SimpleDateFormat("dd/MM/yyyy");
if(bd.parse(birthday, new ParsePosition(0)) == null){
reg_birthday.setError("Esta data não é válida! Preencha novamente, usando o formato dd/mm/aaaa");
validation = false;
时 时
if(validation){
new Register().execute();
时 时
时 时
时 时);
时 时
class Register extends AsyncTask<Void, Void, JSONArray>{
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ctx);
pDialog.setMessage("Aguarde...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
时 时
@Override
protected JSONArray doInBackground(Void... params) {
UserFunctions userFunction = new UserFunctions();
json = userFunction.newUser(fullname, email, login, password, country, genre, birthday, promocode);
return json;
时 时
protected void onPostExecute(JSONArray result) {
// dismiss the dialog once done
pDialog.dismiss();
final AlertDialog alertDialog = new AlertDialog.Builder(
RegisterActivity.this).create();
try {
status = json.getString(0);
msg = json.getString(1);
Log.d("Status", status);
时 时 catch (JSONException e) {
Log.e("RegisterActiviry", "Error converting result " + e.toString());
e.printStackTrace();
status = null;
时 时
if (status.equalsIgnoreCase("erro")){
alertDialog.setTitle("Erro");
alertDialog.setMessage(msg);
时 时else if (status.equalsIgnoreCase("sucesso")){
alertDialog.setTitle("Sucesso!");
alertDialog.setMessage(msg);
finishActivity = true;
时 时else{
alertDialog.setTitle("Erro");
alertDialog.setMessage("Não foi possível realizar seu cadastro, tente novamente mais tarde.");
时 时
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if(finishActivity){
finish();
时 时else{
alertDialog.dismiss();
时 时
时 时
时 时);
alertDialog.show();
时 时
时 时
时 时