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

Não compila o código

Da o seguinte erro: FATAL EXCEPTION: main Meus códigos: FormularioHelper:

package br.com.alura.agenda;

import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;

import br.com.alura.agenda.modelo.Aluno;

/**
 * Created by lucas on 16/04/2017.
 */

public class FormularioHelper {
    private final EditText campoNome, campoEndereco, campoTel, campoSite;
    private final RatingBar campoNota;
    private final ImageView campoFoto;
    private  Aluno aluno;

    public FormularioHelper(FormularioActivity activity){
        campoNome = (EditText) activity.findViewById(R.id.formularioNome);
        campoEndereco = (EditText) activity.findViewById(R.id.formularioEndereco);
        campoTel = (EditText) activity.findViewById(R.id.formularioTelefone);
        campoSite = (EditText) activity.findViewById(R.id.formularioSite);
        campoNota = (RatingBar) activity.findViewById(R.id.formularioNota);
        campoFoto = (ImageView) activity.findViewById(R.id.formularioFoto);
        aluno = new Aluno();

    }

    public Aluno getAluno() {
        aluno.setNome(campoNome.getText().toString());
        aluno.setEndereco(campoEndereco.getText().toString());
        aluno.setTelefone(campoTel.getText().toString());
        aluno.setSite(campoSite.getText().toString());
        aluno.setNota(Double.valueOf(campoNota.getProgress()));
        aluno.setCaminhoFoto((String) campoFoto.getTag());
        return aluno;
    }

    public void preencheFormulario(Aluno aluno) {
        campoNome.setText(aluno.getNome());
        campoEndereco.setText(aluno.getEndereco());
        campoTel.setText(aluno.getTelefone());
        campoSite.setText(aluno.getSite());
        campoNota.setProgress(aluno.getNota().intValue());
        this.aluno = aluno;
    }
}

FormularioActivity:

package br.com.alura.agenda;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;

import br.com.alura.agenda.dao.AlunoDAO;
import br.com.alura.agenda.modelo.Aluno;

public class FormularioActivity extends AppCompatActivity {

    public static final int CODIGO_CAMERA = 567;
    private FormularioHelper helper;
    private String caminho;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        System.out.println("awesfdqFWERHTHRT");
        super.onCreate(savedInstanceState);
        System.out.println("awesfdqFWERHTHRT");
        setContentView(R.layout.activity_formulario);
        try {
            helper = new FormularioHelper(this);
            Intent intent = getIntent();
            Aluno aluno = (Aluno) intent.getSerializableExtra("aluno");
            if (aluno != null){
                helper.preencheFormulario(aluno);
            }

            Button camera = (Button) findViewById(R.id.fomularioBotaoCamera);
            camera.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    caminho = getExternalFilesDir(null) + "/" + System.currentTimeMillis() + ".jpg";
                    File arquivo = new File(caminho);
                    intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(arquivo));
                    startActivityForResult(intentCamera, CODIGO_CAMERA);
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        System.out.println("awesfdqFWERHTHRT");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == RESULT_OK) {
            if (requestCode == CODIGO_CAMERA) {
                ImageView foto = (ImageView) findViewById(R.id.formularioFoto);
                Bitmap bitmap = BitmapFactory.decodeFile(caminho);
                Bitmap bitmapReduzido = Bitmap.createScaledBitmap(bitmap, 300, 300, true);
                if (bitmap == null)
                    Toast.makeText(FormularioActivity.this, "Nulo", Toast.LENGTH_SHORT).show();
                foto.setImageBitmap(bitmapReduzido);
                foto.setScaleType(ImageView.ScaleType.FIT_XY);
                foto.setTag(caminho);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_formulario, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.menu_formulario_ok:{
                Aluno aluno = helper.getAluno();
                AlunoDAO dao = new AlunoDAO(this);

                if (aluno.getId() != null ) {
                    dao.altera(aluno);
                }else{
                    dao.insere(aluno);
                }
                dao.close();

                Toast.makeText(FormularioActivity.this, aluno.getNome() + " salvo!", Toast.LENGTH_SHORT).show();

                finish();
                break;
            }
        }
        return super.onOptionsItemSelected(item);
    }
}

AlunoDAO:

package br.com.alura.agenda.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

import br.com.alura.agenda.modelo.Aluno;

/**
 * Created by lucas on 24/04/2017.
 */

public class AlunoDAO extends SQLiteOpenHelper{

    public AlunoDAO(Context context) {
        super(context, "Agenda", null, 5);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE Aluno(id INTEGER PRIMARY KEY, nome TEXT NOT NULL, endereco TEXT, telefone TEXT, site TEXT, nota REAL, caminhoFoto TEXT);";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String sql = "";
        switch (oldVersion){
            case 4:
                sql = "ALTER TABLE Aluno ADD COLUMN caminhoFoto TEXT";
                db.execSQL(sql);
        }
    }

    public void insere(Aluno aluno) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues dados = salvaDadosDoAluno(aluno);
        db.insert("Aluno", null, dados);
    }

    public List<Aluno> buscaAlunos() {
        String sql = "SELECT * FROM Aluno;";
        SQLiteDatabase db = getReadableDatabase();
        Cursor c = db.rawQuery(sql, null);
        List<Aluno> alunos = new ArrayList<Aluno>();
        while(c.moveToNext()){
            Aluno aluno = new Aluno();
            aluno.setId(c.getLong(c.getColumnIndex("id")));
            aluno.setNome(c.getString(c.getColumnIndex("nome")));
            aluno.setEndereco(c.getString(c.getColumnIndex("endereco")));
            aluno.setTelefone(c.getString(c.getColumnIndex("telefone")));
            aluno.setSite(c.getString(c.getColumnIndex("site")));
            aluno.setNota(c.getDouble(c.getColumnIndex("nota")));
            aluno.setCaminhoFoto(c.getString(c.getColumnIndex("caminhoFoto")));
            alunos.add(aluno);
        }
        c.close();
        return alunos;
    }

    public void exclui(Aluno aluno){
        SQLiteDatabase db = getWritableDatabase();
        String[] params = {String.valueOf(aluno.getId())};
        db.delete("Aluno", "id = ?", params);
    }

    public void altera(Aluno aluno) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues dados = salvaDadosDoAluno(aluno);
        String[] params = {String.valueOf(aluno.getId())};
        db.update("Aluno", dados, "id = ?", params);
    }

    private ContentValues salvaDadosDoAluno(Aluno aluno){
        ContentValues dados = new ContentValues();
        dados.put("nome", aluno.getNome());
        dados.put("endereco", aluno.getEndereco());
        dados.put("telefone", aluno.getTelefone());
        dados.put("site", aluno.getSite());
        dados.put("nota", aluno.getNota());
        dados.put("caminhoFoto", aluno.getCaminhoFoto());
        return dados;
    }
}

ListaAlunosActivity:

package br.com.alura.agenda;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;

import br.com.alura.agenda.dao.AlunoDAO;
import br.com.alura.agenda.modelo.Aluno;

public class ListaAlunosActivity extends AppCompatActivity {

    private ListView listaAlunos;
    private List<Aluno> alunos;
    private AlunoDAO dao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        System.out.println("vdsd");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lista_alunos);
        try {
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            listaAlunos = (ListView) findViewById(R.id.lista_alunos);
            FloatingActionButton add = (FloatingActionButton) findViewById(R.id.ListaAddAluno);
            add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent IntentFormulario = new Intent(ListaAlunosActivity.this, FormularioActivity.class);
                    startActivity(IntentFormulario);
                }
            });

            listaAlunos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> lista, View item, int position, long id) {
                    Aluno aluno = (Aluno) listaAlunos.getItemAtPosition(position);
                    Intent form = new Intent(ListaAlunosActivity.this, FormularioActivity.class);
                    form.putExtra("aluno", aluno);
                    startActivity(form);
                }
            });

        /*listaAlunos.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> lista, View item, int position, long id) {
                Toast.makeText(ListaAlunosActivity.this, "Clique longo", Toast.LENGTH_SHORT).show();
                return false;
            }
        });*/

            registerForContextMenu(listaAlunos);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        carregarTela();
    }

    private void carregarTela() {
        dao = new AlunoDAO(this);
        alunos = dao.buscaAlunos();
        dao.close();
        ArrayAdapter<Aluno> adapter = new ArrayAdapter<Aluno>(this, android.R.layout.simple_list_item_1, alunos);
        listaAlunos.setAdapter(adapter);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, final ContextMenu.ContextMenuInfo menuInfo) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        final Aluno aluno = (Aluno) listaAlunos.getItemAtPosition(info.position);
        //site
        MenuItem itemSite = menu.add("Visitar Site");
        Intent intentSite = new Intent(Intent.ACTION_VIEW);
        //coloca o https na frente
        String site = aluno.getSite();
        if (!site.startsWith("http://")) {
            site = "http://" + site;
        }
        //seta o site
        intentSite.setData(Uri.parse(site));
        itemSite.setIntent(intentSite);

        //sms
        MenuItem itemSms = menu.add("Enviar SMS");
        Intent intentSms = new Intent(Intent.ACTION_VIEW);
        intentSms.setData(Uri.parse("sms:" + aluno.getTelefone()));
        itemSms.setIntent(intentSms);

        //maps
        MenuItem itemMaps = menu.add("Visualizar no mapa");
        Intent intentMaps = new Intent(Intent.ACTION_VIEW);
        intentMaps.setData(Uri.parse("geo:0,0?q=" + aluno.getEndereco()));
        itemMaps.setIntent(intentMaps);

        //Ligar
        MenuItem itemLigar = menu.add("Ligar");
        itemLigar.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if(ActivityCompat.checkSelfPermission(ListaAlunosActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(ListaAlunosActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 1);
                }else {
                    Intent intentLigar = new Intent(Intent.ACTION_CALL);
                    intentLigar.setData(Uri.parse("tel:" + aluno.getTelefone()));
                    startActivity(intentLigar);
                }
                return false;
            }
        });


        MenuItem excluir = menu.add("Excluir");
        excluir.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                dao.exclui(aluno);
                Toast.makeText(ListaAlunosActivity.this, "Excluir o aluno "+ aluno.getNome(), Toast.LENGTH_SHORT).show();
                carregarTela();
                return false;
            }
        });
    }
}

Se alguém souber pq ele para logo depois da instalação eu agradeço!

3 respostas

Lucas, consegue postar a exception para gente ?

Acho que fica mais fácil de descobrirmos o que tá rolando

Esse é o erro que dá:

FATAL EXCEPTION: main
                                                                     Process: br.com.alura.agenda, PID: 20740
                                                                     java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{br.com.alura.agenda/br.com.alura.agenda.ListaAlunosActivity}: java.lang.ClassNotFoundException: Didn't find class "br.com.alura.agenda.ListaAlunosActivity" on path: DexPathList[[zip file "/data/app/br.com.alura.agenda-1/base.apk", zip file "/data/app/br.com.alura.agenda-1/split_lib_slice_8_apk.apk"],nativeLibraryDirectories=[/data/app/br.com.alura.agenda-1/lib/arm, /vendor/lib, /system/lib]]
                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2477)
                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654)
                                                                         at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                         at android.os.Looper.loop(Looper.java:207)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:5728)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
                                                                      Caused by: java.lang.ClassNotFoundException: Didn't find class "br.com.alura.agenda.ListaAlunosActivity" on path: DexPathList[[zip file "/data/app/br.com.alura.agenda-1/base.apk", zip file "/data/app/br.com.alura.agenda-1/split_lib_slice_8_apk.apk"],nativeLibraryDirectories=[/data/app/br.com.alura.agenda-1/lib/arm, /vendor/lib, /system/lib]]
                                                                         at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                                         at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
                                                                         at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
                                                                         at android.app.Instrumentation.newActivity(Instrumentation.java:1072)
                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2467)
                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654) 
                                                                         at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488) 
                                                                         at android.os.Handler.dispatchMessage(Handler.java:111) 
                                                                         at android.os.Looper.loop(Looper.java:207) 
                                                                         at android.app.ActivityThread.main(ActivityThread.java:5728) 
                                                                         at java.lang.reflect.Method.invoke(Native Method) 
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679) 
                                                                         Suppressed: java.lang.ClassNotFoundException: br.com.alura.agenda.ListaAlunosActivity
                                                                         at java.lang.Class.classForName(Native Method)
                                                                         at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
                                                                         at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
                                                                         at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
                                                                                 ... 12 more
                                                                      Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available
solução!

Lucas,

No momento de criação do seu apk por algum motivo ele não conseguiu gerar corretamente.

Vai em Build -> Rebuild Project

Depois tenta instalar novamente