3
I am trying to make a connection to sql server in an Xamarin application for android, however the application presents this error:
Object Reference not set to an instance of an Object
Connection class:
public class SqlServercon
{
SqlConnection conexaoSql;
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
public string CriarStringConexao()
{
builder.UserID = "sa";
builder.Password = "11";
builder.DataSource = "KATHERINE-PC/ONIPRESENTE";
builder.InitialCatalog = "OniPresente";
conexaoSql.ConnectionString = builder.ConnectionString;
return builder.ToString();
}
public List<string> CarregaUsuarios()
{
List<string> lista;
string StringConexaoSql = CriarStringConexao();
string consulta = "SELECT login, senha from Usuarios";
try
{
conexaoSql = new SqlConnection(StringConexaoSql);
conexaoSql.Open();
SqlDataReader rdr = null;
SqlCommand cmd = new SqlCommand(consulta, conexaoSql);
rdr = cmd.ExecuteReader();
lista = new List<string>();
while (rdr.Read())
{
Usuarios u = new Usuarios();
u.Login = rdr["Login"].ToString();
u.Senha = rdr["Senha"].ToString();
lista.Add(u.Login + " " + u.Senha);
}
return lista;
}
catch(Exception ex)
{
throw ex;
}
finally
{
conexaoSql.Close();
}
}
}
Mainactivity:
[Activity(Label = "OniApp", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
private ListView listview;
private Button btnSql;
private List<string> usuarios;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
listview = FindViewById<ListView>(Resource.Id.listView1);
btnSql = FindViewById<Button>(Resource.Id.button1);
listview.ItemClick += ListView_ItemClick;
btnSql.Click += btnSql_Click;
// SetContentView (Resource.Layout.Main);
}
private void btnSql_Click(object sender, EventArgs e)
{
try
{
//conexao com SqlServer
SqlServercon db = new SqlServercon();
Toast.MakeText(this, "Acesso ao SqlServer feito com sucesso", ToastLength.Short).Show();
//carrega a lista de string com dados de usuarios
usuarios = db.CarregaUsuarios();
//exibe os dados ListView
ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, usuarios);
listview.Adapter = adapter;
}
catch(Exception ex)
{
Toast.MakeText(this, "Erro : " + ex.Message, ToastLength.Short).Show();
}
}
private void ListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
using (var dialog = new AlertDialog.Builder(this))
{
//exibe o usuario selecionado
int posicao = e.Position;
string valor = usuarios[posicao];
dialog.SetTitle("Usuario Selecionado");
dialog.SetMessage(valor);
dialog.Show();
}
}
}
Class Usuarios:
public class Usuarios
{
public int IdUsuario { get; set; }
public string Login { get; set; }
public string Senha { get; set; }
public string Nome { get; set; }
public string Chave { get; set; }
public DateTime DtNasc { get; set; }
public string Fone { get; set; }
public string Email { get; set; }
public int OAB { get; set; }
public string Endereco { get; set; }
public string Bairro { get; set; }
public string CEP { get; set; }
public int CodCidade { get; set; }
public string CPF { get; set; }
public string CNPJ { get; set; }
}
Kathe, try for a breakpoint and see where exactly the error is occurring, it can be your connection to the database.
– Marco Souza
Check in the Visual Studio Output window which message is showing at the time this message is shown and paste here for us to see.
– perozzo
Output is empty because the error only occurs in the application.
– Kathe Quandt
Go to Tools/Options, look for the Xamarin item and in Output Verbosity, put "Detailed". Rebuild the project and run in "Debug" mode. When you show this error on the app screen, you should show something in Output. Put @Perozzo in your comment for me to receive the notification.
– perozzo
Press
Ctrl + Alt + E
in Visual Studio and check the checkboxCommon Language Runtime Exceptions
, so you will be able to better analyze where the error is occurring.– Pedro Paulo