Estoy trabajando en una herramienta de búsqueda basado en la consola de "warrants" en un partido que juego que las búsquedas de Google de una hoja de la API de Google Spreadsheets y C #. Originalmente hecho esto en Python y ha funcionado perfectamente, pero tuve un montón de cuestiones que distribuyen mi archivo pitón así que me trasladé a C #.
La API está llamando a los datos perfectamente bien y yo soy capaz de presentar una lista de todos los datos que estaba buscando en el lanzamiento, pero cuando intento y guardarlo en archivos de lista dentro de mi programa me sale el siguiente: Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
También he añadido en una sección que me dice el tipo de datos que estoy llamando con la fila [1] y se dice (sólo una "` ``", tuvo que doblar el formato): System.Collections.Generic.List``1[System.Object]
using Google.Apis.Auth.OAuth2;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Diagnostics;
namespace WarrantSearchProgram
{
class Program
{
static readonly string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
static readonly string ApplicationName = "WarrantSearchProgram";
static readonly string SpreadsheetId = "SpreadsheetId";
static readonly string sheet = "Imported Data";
static SheetsService service;
//List of Warrant Column Variables... Only nameList is being used for now
public static IList<object> testOBJ;
public static List<object> wtStatus;
public static List<object> wtType;
public static List<object> wtNum;
public static IList<object> nameList;
public static List<object> wtCivName;
public static List<object> wtDOB;
public static List<object> wtAddress;
public static List<object> wtJs;
public static List<object> wtCharges;
public static List<object> wtEvidence;
public static List<object> wtReqOfc;
public static List<object> wtReqOfcNum;
static void Main(string[] args)
{
//Set console color and other general settings
Console.Title = "DOJ Warrant Search Program UNOFFICIAL";
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Green;
// Initialization of creds and google sheets
GoogleCredential credential;
using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(Scopes);
}
// Create Google Sheets API service.
service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
//First initilization of warrant sheet info, creates and manages variables.
UpdateSheetData();
while (true)
{
// Main repeating text and SEARCH INPUT
Console.WriteLine("-----------------------------------------------");
Console.WriteLine("Please type in a full name to search for warrants.");
Console.WriteLine("Only ACTIVE warrants will be shown.");
Console.WriteLine("Type in a warrant number to show extra info, including evidence, on just that warrant");
Console.WriteLine("-----------------------------------------------");
Console.Write("Search >>> ");
string searchName = Console.ReadLine();
searchName = searchName.ToUpper();
Console.WriteLine();
Console.Beep();
Console.Clear();
}
}
static void UpdateSheetData()
{
var range = $"{sheet}!A:F";
SpreadsheetsResource.ValuesResource.GetRequest request =
service.Spreadsheets.Values.Get(SpreadsheetId, range);
var response = request.Execute();
IList<IList<object>> values = response.Values;
if (values != null && values.Count > 0)
{
foreach (var row in values)
{
// Calls the row (2nd, name) and displays each name in list
Console.WriteLine("{0}", row[1]);
Console.WriteLine(row.GetType().ToString());
// Attempts to build list of names in program ERROR HERE
nameList.Add(row[1]);
}
}
else
{
Console.WriteLine("No data found.");
}
}
}
}
Quité secciones del código que no tienen nada que ver con esto, así que es más fácil de leer ... Como se puede ver, he intentado IList<object>, List<object>, and List<string>
en diferentes momentos y que no funcionó para mí.
Mi objetivo aquí es cargar cada columna de datos en una lista que entonces puedo realizar búsquedas en el índice, y los datos de pantalla a juego de otras listas. Esto no es muy difícil hacer una vez que puedo cargar los datos arriba en el programa y separarlo. error en la fila 98
De acuerdo con su comentario, en la línea 98 que está intentando Add
un valor al nameList
que no puede ser inicializado. Es por esto que se obtiene el error que haces, Object reference not set to an instance of an object.
- El nameList
no se inició, por lo que no se puede llamar de funciones internas. Es posible que desee crear una instancia que, en cualquier lugar antes de llamar UpdateSheetData
, por ejemplo:
nameList = new List<object>();