Can't use AsyncTask to show ProgressDialog - android

I want to show a ProgressDialog while waiting for server's response.
My class JogarActivity does the following (My app is a quiz game):
1- Initialize variables
2- Verify if it is or not the first question (primeiraPergunta)
2.1- If it's the first question, calls UserFunctions.getJogar(). This function build an list with parameters and send it to a JSONParser class. JSONParser makes the http request and returns a JSONArray with data
2.2- If it isn't the first question, just retrieve the actual question from intent extras.
3- Try to parse JSONArray to string. If the user had already answered all questions in the actual category, this will return an Exception (JSONArray will be null), so it can show a dialog asking user to select another category.
4- Puts all data (question and answer options) on screen and wait for user's interaction.
5- When user select an answer, it calls UserFunctions.gerResposta(). This time, it will return a status message (correct, wrong, error, etc) after updating the database (ponctuation, answered questions etc). It will also retrieve the next question.
6- Show a dialog with info about the question and an OK button that, when pressed, restarts the activity. The next question is passed as intent.putExtra(), and primeiraPergunta (first question?) is setted to false.
*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).
first below i've pasted JogarActivity without changes. Then, I've tried to add an AsyncTask to show the ProgressDialog, but it just doesn't appears on screen (AsyncTask.get() is used to make JogarActivity wait for results from asynctask). Finnaly, i've pasted another class (RegisterActivity) where the AsyncTask works just fine.
I guess AsyncTask is probably not the best approach, but I just want to make it works as soon as possible. This is not my code (except for RegisterActivity). After the app works i'll optimize it :)
==========JogarActivity.java====================
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+"\n\n"+mensagem);
}
else{
alertDialog.setTitle("VOCÊ ERROU");
alertDialog.setMessage("Sua resposta: "+respostaRecebe+"\n\nResposta correta: "+respostaConfere+"\n\n"+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;
}
}
==============JogarActivity with AsyncTask (ProgressDialog doesn't appears)=============
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+"\n\n"+mensagem);
}
else{
alertDialog.setTitle("VOCÊ ERROU");
alertDialog.setMessage("Sua resposta: "+respostaRecebe+"\n\nResposta correta: "+respostaConfere+"\n\n"+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();
}
}
}
=================RegisterActivity (Works fine)======================
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();
}
}
}

put you dialog like below I hope it will work.
runOnUiThread(new Runnable() {
public void run() {
//Your dailog
}
});

Related

Android Spinner's random item id not getting properly

I have a android spinner like this
First one is item name and second one is their respective item id.I want to send respective item id to server when item name is selected and I don't want to desplay item id also.How to resolve this here is my code:
public class Form extends BaseActivity implements AdapterView.OnItemClickListener {
private static final String REGISTER_URL = "http://url/Service.asmx/GenerateTicket";
public static final String PREFS_NAME = "MyPrefsFile";
public static final String CUSTOMERID = "customerId";
public static final String USERNAME = "name";
public static final String HOUSENO = "houseNo";
public static final String LOCALITY = "areaName";
public static final String SERVICE = "serviceId";
public static final String MOBILE = "mobile";
public static final String EMAIL = "email";
public static final String PROBLEM = "jobBrief";
private ProgressDialog pDialog;
Spinner spin;
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
// ArrayList<String> listItems = new ArrayList<>();
// ArrayAdapter<String> adapter;
private List<Item> customerList = new ArrayList<Item>();
private SpinAdapter adapter;
private List<Item> items;
private EditText editname, houseNo, mobile, email, problem;
Spinner service_need;
AutoCompleteTextView autoCompView;
String obj;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.activity_form, frameLayout);
autoCompView = (AutoCompleteTextView) findViewById(R.id.colony);
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.list_item));
autoCompView.setOnItemClickListener(this);
editname = (EditText) findViewById(R.id.name);
houseNo = (EditText) findViewById(R.id.houseNo);
//
mobile = (EditText) findViewById(R.id.mobile);
email = (EditText) findViewById(R.id.email);
problem = (EditText) findViewById(R.id.problem);
Button submit = (Button) findViewById(R.id.submit);
pDialog = new ProgressDialog(this);
cd = new ConnectionDetector(getApplicationContext());
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
//
assert submit != null;
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editname.getText().toString().trim().equals("")) {
Toast.makeText(getApplicationContext(),
"Please enter your name", Toast.LENGTH_SHORT)
.show();
} else if (houseNo.toString().trim().equals("")) {
Toast.makeText(Form.this, "Please enter your house no", Toast.LENGTH_SHORT).show();
} else if (autoCompView.toString().trim().equals("")) {
Toast.makeText(Form.this, "Please enter your locality", Toast.LENGTH_SHORT).show();}
// } else if (service_need.getSelectedItem().toString().trim().equals("Select Service")) {
// Toast.makeText(Form.this, "Please Select item", Toast.LENGTH_SHORT).show();
//
// }
else if (mobile.toString().trim().equals("")) {
Toast.makeText(Form.this, "Please enter your mobile number", Toast.LENGTH_SHORT).show();
}
else if (mobile.getText().length() < 10) {
Toast.makeText(getApplicationContext(),
"Please enter valid mobile number", Toast.LENGTH_SHORT)
.show();
}
else if (problem.toString().trim().equals("")) {
Toast.makeText(Form.this, "Please describe your problem", Toast.LENGTH_SHORT).show();
}
else if (!email.getText().toString().trim().equals(""))
{
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(
email.getText().toString().trim()).matches()) {
Toast.makeText(getApplicationContext(),
"Please enter valid e-mail id", Toast.LENGTH_SHORT)
.show();
}
else {
if (isInternetPresent) {
registerUser();
pDialog.setMessage("Loading...");
pDialog.show();
Toast.makeText(getApplicationContext(),
"connecting...", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(Form.this, "Unable to connect the server, please check your data settings", Toast.LENGTH_LONG)
.show();
}
}
}
else {
// Do your stuff
if (isInternetPresent) {
registerUser();
pDialog.setMessage("Loading...");
pDialog.show();
Toast.makeText(getApplicationContext(),
"connecting...", Toast.LENGTH_SHORT)
.show();
}
else {
Toast.makeText(Form.this, "Unable to connect the server, please check your data settings", Toast.LENGTH_LONG)
.show();
}
}
}
});
//
spin = (Spinner) findViewById(R.id.service_need);
adapter = new SpinAdapter(this, customerList);
spin.setAdapter(adapter);
}
private void registerUser() {
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
final String value=(mSharedPreference.getString("customerId", "Default_Value"));
final String customer_id = value.trim();
final String username = editname.getText().toString().trim();
final String house = houseNo.getText().toString().trim();
final String local_area = autoCompView.getText().toString().trim();
**Something wrong with this line**
**final String service = spin.getSelectedItem().toString().trim();**
final String mobile_no = mobile.getText().toString().trim();
final String email_id = email.getText().toString().trim();
final String prob = problem.getText().toString().trim();
Toast.makeText(Form.this, username.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(Form.this, service.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(Form.this, local_area.toString(), Toast.LENGTH_LONG).show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hidePDialog();
try {
//String result="";
//Do it with this it will work
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject person = jsonarray.getJSONObject(i);
String excep = person.getString("Exception");
String message1 = person.getString("Message");
String job = person.getString("JobNo");
if (excep.equalsIgnoreCase("True")) {
Toast.makeText(Form.this, excep, Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(Form.this, excep, Toast.LENGTH_LONG)
.show();
editname.setText("");
// if email and mb is valid than login
Intent i1 = new Intent(Form.this, Suceessful.class);
i1.putExtra("job_id", job);
startActivity(i1);
finish();
Toast.makeText(Form.this, excep.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(Form.this, message1.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(Form.this, job.toString(), Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Form.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(CUSTOMERID,customer_id);
params.put(USERNAME, username);
params.put(HOUSENO, house);
params.put(LOCALITY, local_area);
params.put(SERVICE, service);
params.put(MOBILE, mobile_no);
params.put(EMAIL, email_id);
params.put(PROBLEM, prob);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
adapter.notifyDataSetChanged();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://url/Service.asmx/GetServiceList");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
result += line;
}
is.close();
//result=sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject obj = jArray.getJSONObject(i);
Item customer = new Item();
customer.setiD(obj.getString("ServiceId"));
customer.setsText(obj.getString("ServiceName"));
// adding movie to movies array
customerList.add(customer);
}
} catch (JSONException e) {
e.printStackTrace();
}
// adapter.notifyDataSetChanged();
return null;
}
protected void onPostExecute(Void result) {
customerList.addAll(items);
adapter.notifyDataSetChanged();
}
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.main, menu);
MenuItem item = menu.findItem(R.id.refresh);
item.setVisible(false);
return true;
}
}
There are several ways to achieve this. I think the simplest way is to create a model class for your spinner item.
public class Item implements Serializable {
public String sText;
public int iD;
public int getiD() {
return iD;
}
public void setiD(int iD) {
this.iD = iD;
}
public Item(String sText, int iD) {
this.sText = sText;
this.iD=iD;
}
public String getsText() {
return sText;
}
public void setsText(String sText) {
this.sText = sText;
}
#Override
public boolean equals(Object o) {
Item item = (Item) o;
if (item.getiD()==iD)
return true;
else
return false;
}
#Override
public String toString() {
return this.sText; // What to display in the Spinner list.
}
}
In the activity class you can create an ArrayAdapter.
private ArrayAdapter adapter;
private List<Item> items;
Inside onCreate initialize list and adapter and set the adapter.
items= new ArrayList<>();
adapter = new ArrayAdapter<Item>(getActivity(), android.R.layout.simple_spinner_item, items);
service_need.setAdapter(adapter);
Replace json parsing like this:
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
// add interviewee name to arraylist
items.add(new Item(jsonObject.getString("ServiceName"),jsonObject.getString("ServiceId")));
}
} catch (JSONException e) {
e.printStackTrace();
}
Then call adapter.notifyDataSetChanged() inside onPostExecute().
In the onClick, you can fetch the customer ID from the spinner.
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String customer_id=customerList.get(spinner_cat.getSelectedItemPosition()).getiD();
To hide the Id you must not add it to the array you are passing to spinner.
Use a structure to create objects with properties name and id.
private static class Items
{
public String name;
public String id;
}
You can add setters and getters methods.
Create a list of Items object. Set each object values for name and id from server.
Create an array of strings for spinner consisting of names of Items objects in order.
On selection event of spinner, get the id of Items object in the list from selected position and use it to send to server.

Solve startActivity in fragment

I have a problem in my code. My problem is related to the startActivity(). When the app is running on the emulator, it does not work. The line causing the problem is described in the end.
I tried to open a new activity (this, newactivity.class), however the problem persists.
UpdateAnsList
public class UpdateAnsList extends Fragment{
/**
* #param args
*/
final static String ARG_POSITION_ANSWER = "position";
private String jsonResult;
private ListView listView;
public int selsub;
public Activity activity;
public String tagsub;
private Context mContext;
private Activity mact;
public UpdateAnsList(Activity _activity){
mact = _activity;
this.activity = _activity;
super.onAttach(_activity);
mContext = this.activity.getApplicationContext();
}
public enum SubSectionAnswer {
TagArt,
TagBio
}
public void StartUpdateAnsList(int v, String o){
tagsub = o;
selsub = v;
SubSectionAnswer currentSub = SubSectionAnswer.valueOf(tagsub);
listView = (ListView) this.activity.findViewById(R.id.listView11);
selectItemAns(selsub,currentSub);
accessWebService();
}
private void selectItemAns(int position, SubSectionAnswer currentSub) {
switch(currentSub){
case TagArt:
switch(position){
case R.id.buttonArt001:
url = "myip/newfolder/question_2.php";
tagdb = "info_general";
break;
case R.id.buttonArt002:
url = "http://myip/newfolder/question_1.php";
tagdb = "info_animation";
break;
case 2:
break;
}
break;
case TagBio:
switch(position){
case R.id.ButtonBio001:
url = "http://myip/newfolder/question_4.php";
tagdb = "info_general";
break;
case R.id.buttonBio002:
url = "http://myip/newfolder/question_5.php";
tagdb = "info_evolution";
break;
case 2:
break;
}
break;
}
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
//Toast.makeText(getApplicationContext(),
// "Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray(tagdb);
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("employee name");
String number = jsonChildNode.optString("content_text");
//String outPut = name + "-" + number;
String outPut = name;
String outPut1 = number;
employeeList.add(createEmployee("Question", outPut,"textlong",number));
}
} catch (JSONException e) {
Toast.makeText(this.activity, "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
//new String[] { "employees" }
//new int[] { android.R.id.text1 }
String[] de = {"Question", "textlong"};
int[] para ={R.id.textView1list11, R.id.textView11 };
SimpleAdapter simpleAdapter = new SimpleAdapter(this.activity, employeeList,
R.layout.activity_item_list_answer,
de, para);
listView.setAdapter(simpleAdapter);
listView.setOnItemClickListener(new ListClickHandler());
//Toast.makeText(getApplication(), "c", Toast.LENGTH_SHORT).show();
}
public class ListClickHandler implements OnItemClickListener{
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {
// TODO Auto-generated method stub
int a =1 ;
//Toast.makeText(mContext, "c", Toast.LENGTH_SHORT).show();
//Intent i = new Intent(mact, QuestionActivity.class);
//mContext.startActivity(i);
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, "test");
// catch event that there's no activity to handle intent
mContext.startActivity(intent);
}
}
private HashMap<String, String> createEmployee(String s1, String s2, String s3,String s4) {
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(s1, s2);
employeeNameNo.put(s3, s4);
return employeeNameNo;
}
}
This is the line causing the problem:
mContext.startActivity(intent);
Screen of debug:
Screen when I use getActivity():
You should start new Activity using Activity context:
getActivity.startActivity(intent);
This is a Fragment class, so you are not able to pass an Intentby simply writing this.startActivity();
What you need to do is to get the Activity of this Fragment class.
So instead of mContext.startActivity(intent); you should write :
getActivity().startActivity(intent);
Basically you are working with Fragment:
How to Start Activity from Fragment:
mContext.startActivity(intent);
Edit 1:
private Context mContext;
public void StartUpdateAnsList(Context ctx, int v, String o){
mContext = ctx;
tagsub = o;
selsub = v;
SubSectionAnswer currentSub = SubSectionAnswer.valueOf(tagsub);
listView = (ListView) this.activity.findViewById(R.id.listView11);
selectItemAns(selsub,currentSub);
accessWebService();
}
Now you can use: mContext.startActivity(intent);
Hope this will help you.

How can i transfer dynamically generated data from one ListView in a screen to another?

My data comes dynamically in an array of textviews and I am entering some data in edit texts beside that.
All the data comes in the listview.
what I need to do is I need to transfer all the data in the text views as well as edittexts to another screen on a button click.
How will I achieve that?
Here is my code:
public class S1 extends ListActivity implements OnClickListener {
private ProgressDialog pDialog;
ListView lv;
Button b;
String arry1[], category_main;
int i,key = 0;
private static String url = "http://ashapurasoftech.com/train/test.json";
private static final String TAG_a = "menu",TAG_Name = "Name",TAG_Cat = "Category";
JSONArray items = null;
ArrayList<HashMap<String, String>> itemList;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.table1);
lv =getListView();
category_main = "";
new Getitems().execute(category_main);
b =(Button) findViewById(R.id.start);
b.setOnClickListener(this);
itemList = new ArrayList<HashMap<String, String>>();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_Name, name);
startActivity(in);
}
});
}
#Override
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.start: try {
onbuttonclick();
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
}
private void onbuttonclick() throws JSONException {
Set<String> arry = new HashSet<String>();
for(int k=0;k<items.length();k++)
{
JSONObject c = items.getJSONObject(k);
String category = c.getString(TAG_Cat);
arry.add(category);
}
arry1 = arry.toArray(new String[arry.size()]);
TableRow[] tr = new TableRow[arry1.length];
TextView[] tx = new TextView[arry1.length];
TableLayout tl = (TableLayout) findViewById(R.id.tablelayout1);
for (i = 0; i < arry1.length; i++) {
final String cat = arry1[i].toString();
tx[i] = new TextView(S1.this);
tx[i].setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tx[i].setText(cat);
tr[i] = new TableRow(S1.this);
tr[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tr[i].addView(tx[i],new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tl.addView(tr[i],new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tx[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
category_main = cat;
if (key==0)
{
key=1;
lv.setVisibility(View.VISIBLE);
}
else if(key==1)
{
key=0;
lv.setVisibility(View.GONE);
}
new Getitems().execute(category_main);
}
});
}
b.setVisibility(View.GONE);
}
private class Getitems extends AsyncTask<Void, Void, Void> {
String cat12 = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(S1.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
}
public void execute(String categorymain) {
cat12 = categorymain;
execute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
items = jsonObj.getJSONArray(TAG_a);
for (i = 0; i < items.length(); i++) {
final JSONObject c = items.getJSONObject(i); String cate12 = c.getString(TAG_Cat);
String name = c.getString(TAG_Name);
final HashMap<String, String> item = new HashMap<String, String>();
if(cat12.equalsIgnoreCase(cate12))
{
item.put(TAG_Name,name);
itemList.add(item);
}
}
}
catch (JSONException e) {
e.printStackTrace();
} finally {
}}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
S1.this, itemList,
R.layout.textview, new String[] {TAG_Name},new int[] { R.id.name});
setListAdapter(adapter);
}
}
}

android lazy list image loading array

so i have been at it for hours and its 4:07 AM now i have to sleep, so i hope someone can help me.
I have an ArrayList of ImageResults objects the class of which is defined as:
public class ImageResults {
String _title, _country, _thumbnailURL, _imageURL;
public ImageResults(String title, String country, String thumbnailURL, String imageURL)
{
_title = title;
_country = country;
_thumbnailURL = thumbnailURL;
_imageURL = imageURL;
}
public String getTitle()
{
return _title;
}
public String getCountry()
{
return _country;
}
public String getThumbnailURL()
{
return _thumbnailURL;
}
public String getImageURL()
{
return _imageURL;
}
}
Now in order to use https://github.com/thest1/LazyList i have to retrieve the thumbnail urls from my arraylist of type imageresults and place them in an array like im doing here
private void populateListBox()
{
String[] imgLst = new String[imagesList.size()];
for(int i = 0; i < imagesList.size();i++)
{
imgLst[i] = (imagesList.get(i)._thumbnailURL);
// Toast t = Toast.makeText(this,imgLst[0] , Toast.LENGTH_SHORT);
// t.show();
}
adapter=new LazyAdapter(this, imgLst);
imageListView.setAdapter(adapter);
}
now the thing is the way it is above is not working but if i take the link individually as follows it works which is the default way the links are organized in the original project
private void populateListBox()
{
String[] imgLst={
"http://www.istartedsomething.com/bingimages/resize.php?i=Velodrome_EN-AU1182456710.jpg&w=300"};
adapter=new LazyAdapter(this, imgLst);
imageListView.setAdapter(adapter);
}
this is how links are organized in the original project, and yest i am 100% sure that both methods are returning the same string just in different ways, one is fetching it from an object in an arraylist and the other im explicitly declaring it.
private String[] mStrings={
"http://www.istartedsomething.com/bingimages/resize.php?i=Velodrome_EN-AU1182456710.jpg&w=300",
"http://www.istartedsomething.com/bingimages/resize.php?i=Velodrome_EN-CA1182456710.jpg&w=300",
"http://a3.twimg.com/profile_images/121630227/Droid_normal.jpg",
"http://a1.twimg.com/profile_images/957149154/twitterhalf_normal.jpg",
"http://a1.twimg.com/profile_images/97470808/icon_normal.png",
"http://a3.twimg.com/profile_images/511790713/AG.png",
"http://a3.twimg.com/profile_images/956404323/androinica-avatar_normal.png",
"http://a1.twimg.com/profile_images/909231146/Android_Biz_Man_normal.png",
"http://a3.twimg.com/profile_images/72774055/AndroidHomme-LOGO_normal.jpg",
"http://a1.twimg.com/profile_images/349012784/android_logo_small_normal.jpg"};
main activity class
public class BngPaperActivity extends Activity {
ListView imageListView;
Spinner countrySpinner;
String selectedMonth;
String selectedYear;
LazyAdapter adapter;
ProgressDialog progress;
Dialog date;
getResult getRes;
String ResultsString;
ArrayList<String> monthList = new ArrayList<String>();
ArrayList<ImageResults> imagesList = new ArrayList<ImageResults>();
String dateText;
TextView selectedDateView;
static final int MONTHYEARDATESELECTOR_ID = 3;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progress = new ProgressDialog(BngPaperActivity.this);
monthList.add("January"); monthList.add("February"); monthList.add("March"); monthList.add("April");
monthList.add("May"); monthList.add("June"); monthList.add("July"); monthList.add("August");
monthList.add("September"); monthList.add("October"); monthList.add("November"); monthList.add("December");
imageListView = (ListView) this.findViewById(R.id.imagesListView);
countrySpinner = (Spinner) this.findViewById(R.id.countrySpinner);
selectedDateView = (TextView) this.findViewById(R.id.selectedDateView);
Button monthYearButton = (Button) this.findViewById(R.id.monthyearBTN);
// set up a listener for when the button is pressed
monthYearButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// call the internal showDialog method using the predefined ID
showDialog(MONTHYEARDATESELECTOR_ID);
}
});
}
private DateSlider.OnDateSetListener mMonthYearSetListener =
new DateSlider.OnDateSetListener() {
public void onDateSet(DateSlider view, Calendar selectedDate) {
// update the dateText view with the corresponding date
dateText = (String.format("%tB %tY", selectedDate, selectedDate));
selectedDateView.setText(dateText);
try {
selectedMonth = monthList.indexOf(String.format("%tB", selectedDate)) + 1 +"";
selectedYear = String.format("%tY", selectedDate);
progress.setMessage("Fetching Images... \nPress Back Button To Cancel");
progress.setCancelable(true);
getRes = new getResult(progress,view);
getRes.execute();
try {
ResultsString = getRes.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
parseResults(ResultsString);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private void parseResults(String result)
{
Scanner scan = new Scanner(result);
String current = scan.nextLine();
String title = "";
String country = "";
String thumbURL = "";
String imageURL = "";
while(!current.equals("End of file"))
{
if(current.equals("Begin Thumb"))
{
current = scan.nextLine();
title = current.substring(current.indexOf(":")+1);
current = scan.nextLine();
country = current.substring(current.indexOf(":")+1);
current = scan.nextLine();
thumbURL = current.substring(current.indexOf(":")+1);
imageURL = thumbURL.replace("300", "900");
current = scan.nextLine();
}
if(current.equals("End Thumb"))
{
imagesList.add(new ImageResults(title,country,thumbURL,imageURL));
}
current = scan.nextLine();
}
populateListBox();
}
private void populateListBox()
{
//this is not working, i would like this one to work
String[] imgLst = new String[imagesList.size()];
for(int i = 0; i < imagesList.size();i++)
{
imgLst[i] = (imagesList.get(i)._thumbnailURL);
// Toast t = Toast.makeText(this,imgLst[0] , Toast.LENGTH_SHORT);
// t.show();
}
//-----------------------------------
/* This is working
String[] imgLst={
"http://www.istartedsomething.com/bingimages/resize.php?i=Velodrome_EN-AU1182456710.jpg&w=300"};
*/
adapter=new LazyAdapter(this, imgLst);
imageListView.setAdapter(adapter);
}
#Override
protected Dialog onCreateDialog(int id) {
// this method is called after invoking 'showDialog' for the first time
// here we initiate the corresponding DateSlideSelector and return the dialog to its caller
final Calendar c = Calendar.getInstance();
final Calendar minDate = Calendar.getInstance();
minDate.set(Calendar.YEAR, 2009);
minDate.set(Calendar.MONTH, Calendar.JUNE);
final Calendar maxDate = Calendar.getInstance();
maxDate.add(Calendar.DATE, 0);
switch (id) {
case MONTHYEARDATESELECTOR_ID:
return new MonthYearDateSlider(this,mMonthYearSetListener,c,minDate,maxDate);
}
return null;
}
private class getResult extends AsyncTask<String, String, String> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog progress;
DateSlider view;
public getResult(ProgressDialog progress, DateSlider view)
{
this.progress = progress;
this.view = view;
}
protected void onPreExecute() {
this.view.dismiss();
this.progress.show();
}
#Override
protected String doInBackground(String... urls) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet("http://devleb.com/BngPaper/BngPaperWebService.php?thumbnail=Yes&year="+selectedYear+"&month="+ selectedMonth));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
//Dialog.dismiss();
progress.dismiss();
return responseString;
}
protected void onPostExecute(Void unused) {
this.progress.dismiss();
if (Error != null) {
Toast.makeText(BngPaperActivity.this, Error, Toast.LENGTH_LONG).show();
}
}
}
}
The following doesn't work?
private void populateListBox()
{
adapter=new LazyAdapter(this, mStrings);
imageListView.setAdapter(adapter);
}
Like in the example given in the lazylist project.

How to use ProgressBar to show a spinner while waiting a httpResponse from server

I'm trying to show a loading icon to the user when the application makes a query to online Database. I've tried using a AnimationDrawable (I gave up because there was no need of a custom icon), ProgressDialog and ProgressBar.
The ProgressBar seems most appropriate, since I don't want a message, just a spinning icon. But I can not even make a ProgressBar appear on the screen, doesn't matter where I call it.
I've got the ProgressDialog appearing in screen, but it only appears after the server's response, and if I use dismiss() or cancel() it doesn't even appear at all.
I've had any success using AsyncTasks or Threads.
In the app, there is a class JogarActivity.java that attemps to show a list of options. It receives some parameters like the user id, and calls UserFunctions:
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);
String 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();
}
}
Below is the getJogar function in userFunctions:
public JSONArray getJogar(String categoria, String usuarioId){
List params = new ArrayList();
params.add(new BasicNameValuePair("categoria", categoria));
params.add(new BasicNameValuePair("idUsuario", usuarioId));
JSONArray json = jsonParser.getJSONFromUrl(perguntaURL, params);
return json;
}
JSONParser.java is the class that makes the httpRequest:
public JSONArray getJSONFromUrl(String url, List params) {
// Making HTTP request
try {
// defaultHttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// json = EntityUtils.toString(httpEntity);
// HttpEntity httpEntity2 = httpEntity;
json = EntityUtils.toString(httpEntity);
// is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//then makes the JSON manipulation
As long as JSONParser and userFunctions aren't activities, I couldn't use ProgressDialogs inside them (Can't get the application context). All server requests are made in JSONParser.java, that's why i've first tried to put the ProgressDialog/ProgressBar there.
The closest that i've reached was using this code in JogarActivity (It shows the ProgressDialog, but after getting server's response. And if I use dismiss, it doesn't even appears)
final ProgressDialog loader = new ProgressDialog(JogarActivity.this);
loader.show();
//...the if-else code i've pasted above
loader.dismiss();
Even using runOnUiThread it doesn't works! I'm getting without options...
Thanks for all help.
this worked:
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();
}
}
}

Categories

Resources