Visual C# Cannot get CSV file to load into a 2D array - csv

I have a very simple .csv file with ID's and serial numbers
the actual application will not know how many rows but will always have two columns
1,16600687
2,16600939
3,16604031
4,16607302
I have everything else setup but i am only loading the data into a 1D array and the comma is remaining in the data
The result i get is string value for 3rd position is 3,16604031
How do i separate this so it is a 2D array with get value [2,0] is 3 and get value [2,1] is 16604031 ?
private void button1_Click(object sender, EventArgs e)
{
string stFileNamenPath = "(put location of file here)";
DialogResult result = openFileDialog1.ShowDialog();
StreamReader sr = new StreamReader(stFileNamenPath);
string[] sortArray = null;
while (!sr.EndOfStream)
{
string strResult = sr.ReadToEnd();
sortArray = strResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
}
string stTest = (string)sortArray.GetValue(2);
MessageBox.Show("string value for 3rd position is " + stTest);
}
CSV file
1,16600687
2,16600939
3,16604031
4,16607302

The answer that comes to my mind is just a LINQ Where statement followed by a Select statement. The former for filtering and the second for actually remaping the data you have. You code would be something like this
string stFileNamenPath = "(put location of file here)";
//DialogResult result = openFileDialog1.ShowDialog();
StreamReader sr = new StreamReader(stFileNamenPath);
string[] sortArray = null;
while (!sr.EndOfStream)
{
string strResult = sr.ReadToEnd();
sortArray = strResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
}
char separator = ',';
var mappedArray = sortArray
.Where(x => !string.IsNullOrEmpty(x) && !string.IsNullOrWhiteSpace(x))
.Select(x => new string[] { x.Split(separator)[0], x.Split(separator)[1] }).ToArray();
var stTest = mappedArray[2][1];
MessageBox.Show("string value for 3rd position is " + stTest);

Related

How to access nested JSON with array in firebase

I want to access a JSON of this structure in firebase
The structure
{
"questions":{
"English":{
"English_2002":[
{
"correct_ans":"A",
"OptionA":"a coder",
"OptionB":"a hacker",
"OptionC":"a writer",
"OptionD":"a programmer",
"Question":"Who build software"
},
{},
{}
],
"English_2003":[],
}
}
}
I want this structure. In the subject structure, other subjects will come after I exhaust 9 years of English.
My confusion is how to logically get each subject since firebase will only accept the root name questions.
Please I may sound dumb, but I have a very long questions thread almost 55000 lines. Because firebase accept one JSON tree.
Sorry i wasn't very clear i was asking from the stack phone app:
I have a question json tag of the structure above; my question is how will i be able to access the object subject like "english":{
// then accessing the first english array "english":[]
//since am now using firebase.
}
initially each array was individual json file, i have to recreate them into one for firebase sake. this is how i was parsing it then.
public class QuestionParser {
Context context;
public QuestionParser(Context c) {
this.context = c;
}
public ArrayList<Question> getJsonFromUrl(String url, String arrayName)
{
ArrayList<Question> arrayofQuestion = new ArrayList<>();
return arrayofQuestion;
}
// Processing question from JSon file in res > raw folder
public ArrayList<Question> parseQuestionJson(int rawJsonFileId, String arrayName) {
ArrayList<Question> questionList = new ArrayList<>();
String jsonstr = null;
try {
InputStream in = context.getResources().openRawResource(rawJsonFileId);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
jsonstr = sb.toString();
Log.d("REEEEADDD" + this.toString(), jsonstr);
//System.out.println(jsonstr);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(jsonstr)) {
return null;
}
try {
JSONObject jsonObject = new JSONObject(jsonstr);
JSONArray jsonArray = jsonObject.getJSONArray(arrayName);
JSONObject jobject;
for (int i = 0; i < jsonArray.length(); i++) {
// TEST
jobject = jsonArray.getJSONObject(i);
String ans = jobject.getString("correct_answer");
String graphic_name = jobject.getString("question_image");
String optionA = jobject.getString("optiona");
String optionB = jobject.getString("optionb");
String optionC = jobject.getString("optionc");
String optionD = jobject.getString("optiond");
String questionNo = jobject.getString("question_number");
String question = jobject.getString("question");
questionList.add(new Question(questionNo, graphic_name, question, optionA, optionB, optionC, optionD, ans));
Log.d("DDD" + this.toString(), String.valueOf(questionList.get(i)));
}
Log.i("ONE QUESTION", questionList.get(50).getQuestion());
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return questionList;
}
}
So how can i parse it from firebase because initially, if a student chooses question and year i passes those value as parameter and use them for parsing. but in firebase now i have access to only root firebase name in the get reference e method
To access for example "correct_ans":"A" you would query your firebase like so:
your.firebase.domain/questions/English/English_2002/0/correct_ans
Notice that each level in the json object is represented by a / and the key you want to access whereas in case of an array you simple add the array index. JSON's simple structure also allows simple REST like access

excel file written in java change the order

I stored data from the database to ArrayList.and I get that data from ArrayList to write on excel file for users download purpose. when I write to excel file, it will write perfectly.but when I write more data the last line called "total" come inside the other lines.coding as below.
public String excel_missedcall(List<datefilter> result1){
Date date = new Date(System.currentTimeMillis());
String download_file="";
Properties prop = new Properties();
InputStream input = null;
String link="";
String linkfilepath="";
//read file name from properties file
try {
String filename = "config.properties";
input = MainController.class.getClassLoader().getResourceAsStream(
filename);
if (input == null) {
System.out.println("Sorry, unable to find " + filename);
}
// load a properties file from class path, inside static method
prop.load(input);
String filepath=prop.getProperty("missedcall_filePath");
download_file=filepath+"missedcall_"+date.getTime()+".xlsx";
link=prop.getProperty("missedcall_downloadfilePath");
linkfilepath=link+"missedcall_"+date.getTime()+".xlsx";
int total=0;
//create excel sheet
//Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet sheet= workbook.createSheet("Missedcall");
//This data needs to be written (Object[])
Map<String, Object[]> data = new TreeMap<String, Object[]>();
data.put("1", new Object[] {"Date", "TotalCalls"});
for(int i=0;i<result1.size();i++){
data.put(""+(i+2),new Object[] {result1.get(i).getMisscall_date(),Integer.parseInt(result1.get(i).getSum_misscall())});
total+=Integer.parseInt( result1.get(i).getSum_misscall());
//System.out.println("**********1*********"+(i+2));
}
data.put(""+(result1.size()+2), new Object[] {"Total", total});
//Iterate over data and write to sheet
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset)
{
System.out.println("*********1**********"+key);
Row row = sheet.createRow(rownum++);
System.out.println("*********2**********"+rownum);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr)
{
Cell cell = row.createCell(cellnum++);
if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Integer)
cell.setCellValue((Integer)obj);
}
}
try
{
//Write the workbook in file system
FileOutputStream out1 = new FileOutputStream(new File(download_file));
workbook.write(out1);
out1.close();
System.out.println("xlsx written successfully on disk.");
}
catch (Exception e)
{
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return linkfilepath;
}
Output of excel file is:
Date TotalCalls
2015-08-28 1895
2015-08-29 599
2015-08-30 354
2015-08-31 2028
Total 6712
2015-08-20 0
2015-08-21 0
2015-08-22 2
2015-08-23 12
2015-08-24 22
2015-08-25 324
2015-08-26 878
2015-08-27 598
Please help me.
You are using String as key , replace following line
Map<String, Object[]> data = new TreeMap<String, Object[]>();
with
Map<Integer, Object[]> data = new TreeMap<Integer, Object[]>();

how to reverse the extracted entry after modification

I am working with csv file having very large dataset. while reading file i had extracted 4th place(BALANCE) ';' separated numeric value from each rows through while loop iteration. and make a list of Double after some mathematical calculation(here incremented).
now I want to store this list of Double in reverse order(from end to beginning).as its original position(here 4th place).example
public static void main(String[] args) throws IOException {
String filename = "abc.csv";
List<Double> list = new ArrayList<Double>();
File file = new File(filename);
Scanner inputStream = new Scanner(file);
inputStream.next();
while (inputStream.hasNext()) {
String data = inputStream.next();
String[] values = data.split(";");
double BALANCE = Double.parseDouble(values[1]);
BALANCE = BALANCE + 1;
ListIterator li = list.listIterator(list.size());
while (li.hasPrevious()) {
values[1] = String.valueOf(li.previous()); }
inputStream.close();
}
} }
You can use Collections.reverse. Example Collections.reverse(list);

Convert Byte Array into List Windows phone 8

I am using this piece of code to convert List into byte array but again I want to convert to this data into List how it is possible.
List<String> stringlist = new List<String>();
stringlist.Add("Oye Oye");
stringlist.Add("Hello hello");
byte[] byteArr = stringlist.SelectMany(s => System.Text.Encoding.UTF8.GetBytes(s)).ToArray();
In your example it isn't possible, because you have no way to tell where a string ends and where the next one starts. It would be possible by using a separator (the character \0 is often used to indicate the end of a string):
List<String> stringlist = new List<String>();
stringlist.Add("Oye Oye");
stringlist.Add("Hello hello");
byte[] byteArr = stringlist.SelectMany(s => System.Text.Encoding.UTF8.GetBytes(s + '\0').ToArray();
You can then retrieve your list by using the Split method:
var stringList = System.Text.Encoding.UTF8.GetString(byteArr, 0, byteArr.Length).Split('\0');
But overall I don't think it's a good idea. Depending on what you need, I'd rather recommend to use the DataContractSerializer to convert your array to bytes:
var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(List<string>));
byte[] byteArr;
using (var ms = new System.IO.MemoryStream())
{
serializer.WriteObject(ms, stringlist);
byteArr = ms.ToArray();
}
And to convert it back:
using (var ms = new System.IO.MemoryStream(byteArr))
{
stringlist = (Sserializer.ReadObject(ms);
}

How can I parse JSON in Windows Phone?

I would like to parse this page
That page has json data like this :
{"List":[{"num":"1","name":"hello","ox_score":"30","between_score":"30","order_score":"30","total_score":"90"}]}
I tried below code.(I used JSON.NET) but I was concerend about "List" and I also tried JArray and... o["Lists"]["name"] but I couldn't get a right results. The below code also return null messages.
Please help me out.
code
public void connection()
{
string uriString = "http://kah601.cafe24.com/jp_mango_loadboard.php";
WebClient wc = new WebClient();
wc.Headers["Accept"] = "application/json";
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.DownloadStringAsync(new Uri(uriString));
}
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
JObject o = JObject.Parse(e.Result);
String name = (string) o["name"];
String ox_score = (string) o["ox_score"];
String between_score = (string) o["between_score"];
String order_score = (string) o["order_score"];
String total_score = (string) o["total_score"];
String rank_result = name + ox_score + between_score + order_score + total_score;
MessageBox.Show(rank_result);
}
Given it is a list, you should index the elements of the JArray. Here is a sample code to help you out (Notice the [0] => referencing the 1st element of the JArray):
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
JObject o = JObject.Parse(e.Result);
JArray a = (JArray)o["List"];
Debug.WriteLine("{0}", (String)a[0]["name"]);
}