how to export a text file with PadRight space android - android

I want to ask export data to text file with spaces(PadRight) like this
Date (max 10 characters) and Barcode (max 14 characters) and Qty 1 (max 8 characters) and Qty 2 (max 8 characters)
Date Barcode Q1 Q2
--------------------------------------
21/03/2022,123456 ,10 ,4
21/03/2022,0909 ,3 ,9
now i don't use spaces(pad) like this
Date Barcode Q1 Q2
21/03/2022,123456,10,4
21/03/2022,0909,3,9
This is my code
btn_export.setOnClickListener(new View.OnClickListener() {
SQLiteDatabase db = controller.getReadableDatabase();
Cursor c = null;
#Override
public void onClick(View v) { //main code begins here
try {
c = db.rawQuery("select TanggalScan,KodeBarcode,QtyGudang,QtyToko from tblscandata", null);
int rowcount = 0;
int colcount = 0;
File sdCardDir = Environment.getExternalStorageDirectory();
String filename = "OPANAME.txt";
File saveFile = new File(sdCardDir,filename);
FileWriter fw = new FileWriter(saveFile);
Log.e("File path", filename);
BufferedWriter bw = new BufferedWriter(fw);
rowcount = c.getCount();
colcount = c.getColumnCount();
if (rowcount > 0) {
c.moveToFirst();
for (int i = 0; i < rowcount; i++) {
c.moveToPosition(i);
for (int j = 0; j < colcount; j++) {
if (j != colcount - 1)
bw.write(c.getString(j) + ",");
else
bw.write(c.getString(j));
}
bw.newLine();
}
bw.flush();
lbl.setText("Exported Successfully.");
controller = new DBController(getApplicationContext());
SQLiteDatabase db = controller.getWritableDatabase();
db.execSQL("delete from " + DBController.TableScan);
}
} catch (Exception ex) {
if (db.isOpen()) {
db.close();
lbl.setText(ex.getMessage().toString());
}
} finally {
}
}
});
this my code

Related

Filter number from Array of string and get the index of last two greater number in android

I have a ArrayList that has value like [Value,Sum3,121,data8input,in:21::7,7.00,9.01] and I want to extract only number as the output should be like this [3,121,8,21,7,7.00,9.01] and then have to rearrange ascending and then get the index of last two number as result will be [21,121].
My tried code below,
for (int i = 0; i < arrayString.size(); i++) {
Pattern p = Pattern.compile("-?\\d+(,\\d+)*?\\.?\\d+?");
List<String> numbers = new ArrayList<String>();
Matcher m = p.matcher(arrayString.get(i).getvalue);
numbers.addAll(m);
for (int j = 0; j < numbers.size(); j++) {
Log.d("REMEMBERFILTER", allCollection.get(i).getTextValue());
}
}
}
do something like this, though it is not exactly memory efficient as I am using another list.
ArrayList<String> tempList = new ArrayList<>();
for (int i = 0; i < yourArrayList.size(); i++) {
tempList.add(yourArrayList.get(i).replaceAll("[^0-9]", ""));
}
//Arrange in ascending order
Collections.sort(tempList);
//Also try to remove those indexes which has only letters with
tempList.removeAll(Arrays.asList("", null));
for (int i = 0; i < tempList.size(); i++) {
Log.d("+++++++++", "" + tempList.get(i));
}
//You can get the last two or any element by get method of list by //list.size()-1 and list.size()-2 so on
This is a way to do it, finalArray has the 2 numbers you want:
String[] str = new String[] {"Value", "Sum3", "121", "data8input", "in:21::7", "7.00,9.01"};
StringBuilder longStringBuilder = new StringBuilder();
for (String s : str) {
longStringBuilder.append(s).append(" ");
}
String longString = longStringBuilder.toString();
String onlyNumbers = " " + longString.replaceAll("[^0-9.]", " ") + " ";
onlyNumbers = onlyNumbers.replaceAll(" \\. ", "").trim();
while (onlyNumbers.indexOf(" ") > 0) {
onlyNumbers = onlyNumbers.replaceAll(" ", " ");
}
String[] array = onlyNumbers.split(" ");
Double[] doubleArray = new Double[array.length];
for (int i = 0; i < array.length; i++) {
try {
doubleArray[i] = Double.parseDouble(array[i]);
} catch (NumberFormatException e) {
e.printStackTrace();
doubleArray[i] = 0.0;
}
}
Arrays.sort(doubleArray);
int numbersCount = doubleArray.length;
Double[] finalArray;
if (numbersCount >= 2) {
finalArray = new Double[]{doubleArray[numbersCount - 2], doubleArray[numbersCount - 1]};
} else if (numbersCount == 1) {
finalArray = new Double[]{ doubleArray[0]};
} else {
finalArray = new Double[]{};
}
for (Double number : finalArray) {
System.out.println(number);
}

Android. How to switch String = (A B, C D, E F, .....) to String (B A, D C, F E, ......)

i am a beginner.
I get String from SQLite.
WKT = cursor.getString(cursor.getColumnIndex(polygon));
WKT = WKT.replaceAll(",", ", ");
Its look like String = (1.00 2.00, 3.00 4.00, 5.00 6.00, .....).
How to switch it to String (2.00 1.00, 4.00 3.00, 6.00 5.00, ......).
Thanks.
try this
private static void testMethod() {
String result = "(A B, C D, E F)";
String resultTmp = result;
resultTmp = resultTmp.replace("(", "");
resultTmp = resultTmp.replace(")", "");
String[] aryResult = resultTmp.split(",");
String[] finalResult = reverseString(aryResult);
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < finalResult.length; i++) {
String dfgf = strBuilder.toString().equals("") ? "" : ",";
strBuilder.append(dfgf);
strBuilder.append(finalResult[i]);
}
String newString = strBuilder.toString();
System.out.println("RESULT : " + newString);
}
public static String[] reverseString(String[] words)
{
String[] t = new String[words.length];
for (int i = 0; i < words.length; i++)
{
t[i] = "";
for (int j = words[i].length() - 1; j >= 0; j--)
t[i] += words[i].charAt(j);
}
return t;
}
Follow below steps
1)Split string with ","
2)User Reverse() function to reverse the string(AB->BA)
3)Store the result in to an array.
Repeat the step until you split the last entry from sql lite.
Try this logic,its working in c and c++.
int Groups = 1; // Count 1 for the first group of letters
for ( int Loop1 = 0; Loop1 < strlen(String); Loop1++)
if (String[Loop1] == ' ') // Any extra groups are delimited by space
Groups += 1;
int* GroupPositions = new int[Groups]; // Stores the positions
for ( int Loop2 = 0, Position = 0; Loop2 < strlen(String); Loop2++)
{
if (String[Loop2] != ' ' && (String[Loop2-1] == ' ' || Loop2-1 < 0))
{
GroupPositions[Position] = Loop2; // Store position of the first letter
Position += 1; // Increment the next position of interest
}
}
try this..
private static void testTwo() {
String result = "(1.00 2.00, 3.00 4.00, 5.00 6.00)";
String resultTmp = result;
resultTmp = resultTmp.replace("(", "");
resultTmp = resultTmp.replace(")", "");
String[] aryResult = resultTmp.split(",");
for (int i = 0; i < aryResult.length; i++) {
String str = aryResult[i].trim();
String[] sdf = str.split(" ");
aryResult[i] = reverseArray(sdf);
}
String strResult = Arrays.toString(aryResult).replace("[", "(").replace("]", ")");
System.out.println("RESULT : " + strResult);
}
public static String reverseArray(String[] words)
{
for(int i = 0; i < words.length / 2; i++)
{
String temp = words[i];
words[i] = words[words.length - i - 1];
words[words.length - i - 1] = temp;
}
return ((Arrays.toString(words)).replace("[", "")).replace("]", "").replace(",", "");
}
#. If you want to swap sub-string, just use below method:
public String swapString(String str) {
str = str.replace("(", "");
str = str.replace(")", "");
String[] array = str.split(", ");
StringBuilder result = new StringBuilder();
result.append("(");
for (int i = 0; i < array.length; i++) {
String[] temp = String.valueOf(array[i]).split(" ");
result.append(temp[1]);
result.append(" ");
result.append(temp[0]);
if (i != array.length -1)
result.append(", ");
}
result.append(")");
return result.toString();
}
USE:
String yourString = "(1.00 2.00, 3.00 4.00, 5.00 6.00)";
Log.d("ARRAY", "Before Swap: " + yourString);
yourString = swapString(yourString);
Log.d("ARRAY", "After Swap: " + yourString);
OUTPUT:
D/ARRAY: Before Swap: (1.00 2.00, 3.00 4.00, 5.00 6.00)
D/ARRAY: After Swap: (2.00 1.00, 4.00 3.00, 6.00 5.00)
#. If you want to swap char, use below method:
public String swapChar(String str) {
// Convert string to char array
char[] array = str.toCharArray();
for (int i = 1; i < array.length - 1; i+=5) {
// Swap char
char temp = array[i];
array[i] = array[i+2];
array[i+2] = temp;
}
return String.valueOf(array);
}
USE:
String yourString = "(A B, C D, E F, G H, I J)";
Log.d("ARRAY", "Before Swap: " + yourString);
yourString = swapChar(yourString);
Log.d("ARRAY", "After Swap: " + yourString);
OUTPUT:
D/ARRAY: Before Swap: (A B, C D, E F, G H, I J)
D/ARRAY: After Swap: (B A, D C, F E, H G, J I)
Hope this will help~

save image in db erro & decodeByteArray give null

I am trying to download image and save it to db i download it and save i to BLOB field when want to retrieve it it get me null value.I search a lot and examine lots of things but I have no idea where is the problem :( .
save image part :
MyDataBase = new MyDatabase(this);
mydb = MyDataBase.getWritableDatabase();
byte[] tempval;
for (int j = 0; j < myarray.arrtitle.length; j++)
{
tempval = saveimage(myarray.arrpic.get(j),myarray.arrpath[j]);
mydb.execSQL("INSERT INTO news (title,content,image) VALUES (\"" + myarray.arrtitle[j] +
"\",\"" + myarray.arrcontent[j] + "\",\"" + tempval + "\")");
}
mydb.close()
saveimage() function :
try {
////////////////get bitmap to byte
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] image = bos.toByteArray();
return image;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
read from db:
try
{
String temp = null;
Bitmap tempbit = null;
ArrayList<Bitmap> tempbit2 = new ArrayList<Bitmap>();
ArrayList<String> tempstring = new ArrayList<String>();
MyDataBase = new MyDatabase(this);
mydb = MyDataBase.getReadableDatabase();
Cursor cu = mydb.rawQuery("SELECT * FROM news",null);
cu.moveToFirst();
for (int i = 0;i<cu.getCount();i++)
{
temp = cu.getString(cu.getColumnIndex("title"));
byte[] imag = cu.getBlob(cu.getColumnIndex("image"));
tempbit = BitmapFactory.decodeByteArray(imag, 0, imag.length); // i get null here
tempbit2.add(tempbit);
tempstring.add(temp);
cu.moveToNext();
Toast.makeText(getApplicationContext(), "" + tempbit + i, Toast.LENGTH_LONG).show();
}
////////////////////////////show in list view
ListViewAdapte adapter = new ListViewAdapte(Description.this, R.layout.listview, tempstring , tempbit2);
MyList.setAdapter(adapter);
MyList.setOnItemClickListener(this);
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), "error on load from db", Toast.LENGTH_LONG).show();
}
When I Toast tempbit it gets me null
i should save picture as contentview
ContentValues tempval = new ContentValues();
for (int j = 0; j < myarray.arrtitle.length; j++)
{
mydb.execSQL("INSERT INTO news (title,content) VALUES (\"" + myarray.arrtitle[j] +
"\",\"" + myarray.arrcontent[j] + "\"" + ")");
}
for (int j = 0; j < myarray.arrpic.size(); j++)
{
tempval = saveimage(myarray.arrpic.get(j),myarray.arrpath[j]);
update ="title ='" + myarray.arrtitle[j] + "'" ;
mydb.update("news", tempval,update, null);
}
save image is possible with using contentview :)

comments need for exporting android Sqlite DB to CSV

I am trying to export the SQLite db of the app to CSV file and store in SD card. The exporting method was defined in DBAdapter class as ExportToCSV. I have check that the app create a SQLite database successfully. However, when I try to call ExportToCSV using onPause method in MainActivity, the app can not response to export the database. Can you give me any comments on how to correct this code? I will appreciate your help!
My code is as follows:
public void ExportToCSV(Cursor c, String fileName) {
int rowCount = 0;
int colCount = 0;
FileWriter fw;
BufferedWriter bfw;
File sdCardDir = Environment.getExternalStorageDirectory();
File saveFile = new File(sdCardDir, fileName);
try {
rowCount = c.getCount();
colCount = c.getColumnCount();
fw = new FileWriter(saveFile);
bfw = new BufferedWriter(fw);
if (rowCount > 0) {
c.moveToFirst();
// write the colume title
for (int i = 0; i < colCount; i++) {
if (i != colCount - 1)
bfw.write(c.getColumnName(i) + ',');
else
bfw.write(c.getColumnName(i));
}
// change the line
bfw.newLine();
// write data
for (int i = 0; i < rowCount; i++) {
c.moveToPosition(i);
Log.v("exporting data", "exportting" + (i + 1) + "line");
for (int j = 0; j < colCount; j++) {
if (j != colCount - 1)
bfw.write(c.getString(j) + ',');
else
bfw.write(c.getString(j));
}
// change line
bfw.newLine();
}
}
I use onPause in MainActivity.java to call ExportToCSV:
#Override
protected void onPause() {
super.onPause();
DBAdapter myDatabase=new DBAdapter(this);
myDatabase.open();
Cursor c=myDatabase.getAllgpspoint();
// this method was defined in DBAdapter.java and returned a Cursor
myDatabase.ExportToCSV(c, "IRI.csv");
myDatabase.close();
mSensorManager.unregisterListener(this);
}
You must close the file at the end.
bfw.close();

Android update sqlite table

I have written Update table using dbAdapter.
public void loadDownloadData() {
SoapPrimitive responsePrimitiveData;
//Loop Table list
for (int i = 0; i < tablesName.size(); i++) {
try {
responsePrimitiveData = soapPrimitiveData(tablesName.get(i));
if (responsePrimitiveData != null) {
try {
String result = responsePrimitiveData.toString();
JSONObject jsonobject = new JSONObject(result);
JSONArray array = jsonobject.getJSONArray("Table1");
int max = array.length();
// Loop each table data
for (int j = 0; j < max; j++) {
JSONObject obj = array.getJSONObject(j);
JSONArray names = obj.names();
StringBuilder strFields = new StringBuilder();
StringBuilder strValues = new StringBuilder();
String[] strToFields = new String[names.length()];
String[] strToFieldsVal = new String[names.length()];
//getting the Json name, values in separate string array
for (int k = 0; k < names.length(); k++) {
String name = names.getString(k);
strToFields[k] = names.getString(k);
String strVal;
if(obj.getString(name)== null){
strVal="";
strToFieldsVal[k]="";
}else{
if(obj.getString(name).equals(" ")){
strVal="";
strToFieldsVal[k]="";
}else{
String tmp1 = obj.getString(name).replaceAll("\\s+", " ");
String tmp = tmp1.replaceAll("\\s+", " ");
strVal =tmp.replaceAll("\\s+", " ");
strToFieldsVal[k]=strVal;
}
}
strFields.append(name + ",");
strValues.append(strVal+",");
} //end of json for loop
strFields.deleteCharAt(strFields.length() - 1);
strValues.deleteCharAt(strValues.length() - 1);
if(getTableUpdateType(tablesName.get(i)).equals("1")){
String actualtable = getAndroidTablename(tablesName.get(i));
if(isTableRecords(tablesName.get(i))){
String[] strWhereField = getTablePrimaryKey(tablesName.get(i),strBusinessUnit);
String[] strWhereFieldVal = new String[strWhereField.length];
StringBuilder whereFields = new StringBuilder();
for (int a = 0; a < strWhereField.length; a++) {
strWhereFieldVal[a] = obj.getString(strWhereField[a]);
whereFields.append(strWhereField[a] + "= ? and ");
}
whereFields.delete(whereFields.length() - 4, whereFields.length());
updateTableRecords(actualtable, strToFields, strToFieldsVal,whereFields.toString() ,strWhereFieldVal);
}else{
insertTableRecords(actualtable, strToFields, strToFieldsVal);
}
}else if(getTableUpdateType(tablesName.get(i)).equals("2")){
}else if(getTableUpdateType(tablesName.get(i)).equals("3")){
}else{
}
}//end of each table data
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
and I called like update method:
public void updateTableRecords(String strTableName, String[] strToFields, String[] strValues,String strWhereField ,String[] strWhereFieldVal){
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(DownlaodTableActivity.this);
dbAdapter.openDataBase();
ContentValues initialValues = new ContentValues();
for(int i=0 ;i<strToFields.length;i++){
initialValues.put(strToFields[i],strValues[i]);
}
long n = dbAdapter.updateRecordsInDB(strTableName, initialValues, strWhereField, strWhereFieldVal);
System.out.println( " -- n--- " + n);
Toast.makeText(DownlaodTableActivity.this, n+" rows updated", Toast.LENGTH_SHORT).show();
}
I want to generate update statement dynamic way. From These code I put Where part also.But I did not generate where clause.
see :
UPDATE strTableName SET ExecutiveCode=?, FreeIssuePrefix=?, DisPaySchedulePrefix=?, NextFreeIssueNo=?, NextReturnNo=?, UploadedType=?, DisNextFOCNo=?, DisNextFreeIssueNo=?
Please help me How to give the Where clase(Here I gave String & arguments as string array)
Thanks in advance...
try like this
dbAdapter.updateRecordsInDB(strTableName, initialValues,""+whereField+"='"+whereFieldValue+"'",null);
if your whereField field's type is number then don't use ''
If you have to compare with multiple values use
String where="";
for(int i=0;i<strWhereField.length();i++)
{
where=where+whereField[i]+"='"+strWhereFieldValue[i]+"'"
if(i<(strWhereField.length()-1)) where=where+" and"
}
dbAdapter.updateRecordsInDB(strTableName, initialValues,where,null);

Categories

Resources