Solucionado (ver solução)
Solucionado
(ver solução)
3
respostas

FATAL EXCEPTION: AsyncTask #1

Olá. Já verifiquei o código e está tudo correto, mas ao finalizar o status de envio, barra de progressão finalizada, o app finaliza e fecha a aplicação.


06-02 21:11:59.331 20302-20902/br.com.jacquesalexandre.agenda1 E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
    Process: br.com.jacquesalexandre.agenda1, PID: 20302
    java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:318)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at java.lang.Thread.run(Thread.java:761)
     Caused by: java.util.NoSuchElementException
public class EnviaAlunosTask extends AsyncTask <Void, Void, String> {

    private Context context;
    private ProgressDialog dialog;

    public EnviaAlunosTask(Context context) {
        this.context = context;
    }

    @Override
    protected void onPreExecute() {
        dialog = ProgressDialog.show(context, "Aguarde", "Enviado alunos...", true, true);
    }

    @Override
    protected String doInBackground(Void... params) {

        AlunoDAO dao = new AlunoDAO(context);
        List<Aluno> alunos = dao.buscaAlunos();
        dao.close();

        AlunoConverter conversor = new AlunoConverter();
        String json = conversor.converteparaJSON(alunos);

        WebClient client = new WebClient();
        String resposta = client.post(json);

        return resposta;
    }

    @Override
    protected void onPostExecute(String resposta) {
        dialog.dismiss();
        Toast.makeText(context, resposta, Toast.LENGTH_LONG).show();
    }
}

...public class ListaAlunosActivity... @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_lista_alunos, menu); return true; }

public class WebClient {

    public String post(String json){
        try {
            URL url = new URL("http://www.caelum.com.br/mobile");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Content-type", "application/json");
            connection.setRequestProperty("Accept", "application/json");

            connection.setDoOutput(true);

            PrintStream outPut = new PrintStream( connection.getOutputStream());
            outPut.println(json);

            connection.connect();

            Scanner scanner = new Scanner(connection.getInputStream());
            String resposta = scanner.next();
            return resposta;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
public class AlunoConverter {

    public String converteparaJSON(List<Aluno> alunos) {
        JSONStringer js = new JSONStringer();

        try {
            js.object().key("List").array().object().key("aluno").array();
            for(Aluno aluno : alunos){
                js.object();
                js.key("nome").value(aluno.getNome());
                js.key("nota").value(aluno.getNota());
                js.endObject();
            }
            js.endArray().endObject().endArray().endObject();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return js.toString();
    }
}

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.menu_enviar_notas:
                new EnviaAlunosTask(this).execute();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
3 respostas

Jacques, de boa ?

Cara eu acho que o correto é a chave list em minusculo, altera isso e fala para gente o que tá rolando.

Olá Matheus. Alterei a chave e não deu certo. Estou utilizando meu celular para testar o APP e não o emulador do AndroidStudio. Abaixo segue o logCat:

06-04 12:31:21.189 23240-24176/br.com.jacquesalexandre.agenda1 E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
    Process: br.com.jacquesalexandre.agenda1, PID: 23240
    java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:318)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at java.lang.Thread.run(Thread.java:761)
     Caused by: java.util.NoSuchElementException
        at java.util.Scanner.throwFor(Scanner.java:874)
        at java.util.Scanner.next(Scanner.java:1388)
        at br.com.jacquesalexandre.agenda1.WebClient.post(WebClient.java:27)
        at br.com.jacquesalexandre.agenda1.EnviaAlunosTask.doInBackground(EnviaAlunosTask.java:39)
        at br.com.jacquesalexandre.agenda1.EnviaAlunosTask.doInBackground(EnviaAlunosTask.java:14)
        at android.os.AsyncTask$2.call(AsyncTask.java:304)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
        at java.lang.Thread.run(Thread.java:761) 
06-04 12:31:22.310 23240-23240/br.com.jacquesalexandre.agenda1 E/WindowManager: android.view.WindowLeaked: Activity br.com.jacquesalexandre.agenda1.ListaAlunosActivity has leaked window DecorView@aa8be0f[Aguarde] that was originally added here
        at android.view.ViewRootImpl.<init>(ViewRootImpl.java:424)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:331)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
        at android.app.Dialog.show(Dialog.java:316)
        at android.app.ProgressDialog.show(ProgressDialog.java:116)
        at android.app.ProgressDialog.show(ProgressDialog.java:104)
        at br.com.jacquesalexandre.agenda1.EnviaAlunosTask.onPreExecute(EnviaAlunosTask.java:25)
        at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:613)
        at android.os.AsyncTask.execute(AsyncTask.java:560)
        at br.com.jacquesalexandre.agenda1.ListaAlunosActivity.onOptionsItemSelected(ListaAlunosActivity.java:105)
        at android.app.Activity.onMenuItemSelected(Activity.java:3208)
        at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:368)
        at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
        at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
        at android.support.v7.app.AppCompatDelegateImplV9.onMenuItemSelected(AppCompatDelegateImplV9.java:674)
        at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
        at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
        at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
        at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:963)
        at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:624)
        at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:150)
        at android.view.View.performClick(View.java:5612)
        at android.view.View$PerformClick.run(View.java:22285)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6123)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
solução!

Vi dois detalhes no seu webcliente, primeiro que não falou que a requisição é do tipo post:

connection.setRequestMethod("POST");

Outro detalhe é que a url é https invés de http