save image in db erro & decodeByteArray give null - android

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 :)

Related

how to export a text file with PadRight space 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

how to recursively copySDcard directory and subdirectory to other smb directory(samba)?

i am using Jcifs library.
i try this code is working copy parent directory and file but sub directory not copy..
calling function
for (int j = 0; j < AppConst.checkfilelist.size(); j++) {
String old = AppConst.checkfilelist.get(j);
Log.d("smb_c_check_item", "" + AppConst.checkfilelist.get(j));
copyToDirectory(old, AppConst.destinationpath);
}
Function
public int copyToDirectory(String old, String newDir) {
try {
SmbFile old_file = new SmbFile(old);
SmbFile temp_dir = new SmbFile(newDir);
Log.d("smb_c_sour:desti_dir", "" + old + "---" + newDir);
// copy file
if (old_file.isFile()) {
Log.d("smb_c_file","yes");
String file_name = old.substring(old.lastIndexOf("/"), old.length());
Log.d("smb_c_file_name", "" + file_name);
String servername="smb://+ ipaddress+/";
NtlmPasswordAuthentication auth1 = new NtlmPasswordAuthentication(servername, "", "");
// smb file path
SmbFile cp_smbfile = new SmbFile(newDir + file_name.substring(1),auth1);
Log.d(" smb_c_file_path", "" + cp_smbfile);
if (!cp_smbfile.exists())
cp_smbfile.createNewFile();
cp_smbfile.connect();
InputStream in = new FileInputStream(String.valueOf((old_file)));
SmbFileOutputStream sfos = new SmbFileOutputStream(cp_smbfile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
sfos.write(buf, 0, len);
}
// copy directory
} else if (old_file.isDirectory()) {
String servername="smb://+ ipaddress+/";
NtlmPasswordAuthentication auth1 = new NtlmPasswordAuthentication(servername, "", "");
Log.d("smb_c_folder","yes");
String files[] = old_file.list();
int len = files.length;
Log.d("smb_c_dirlength", "" + len);
for(int i1=0;i1<len;i1++){
Log.d("smb_c_dir---",""+files[i1]);
}
// remove last character
old = old.substring(0, old.length() - 1);
// get dir name
String old_f = old.substring(old.lastIndexOf("/"), old.length());
Log.d("smb_c_old_f", "" + old_f);
//create smbfile path
SmbFile smbdir = new SmbFile(newDir + old_f.substring(1),auth1);
// create new directory
if (!smbdir.exists()) {
Log.d("smb_c_mkdir", "created");
smbdir.mkdirs();
//return -1;
}
Log.d("smb_c_dir", "" + smbdir);
for (int i = 0; i < len; i++) {
copyToDirectory(old + "/" + files[i], smbdir + "/");
Log.d("smb_copy_rec", "" + old + "/" + files[i] + ":" + smbdir + "/");
}
} else if (!temp_dir.canWrite())
Log.d("smb_c_dir_noperm","yes");
return -1;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
Thanx in advance for any suggestions or help.sorry for my bad eng..
i found solution..
public int copySdToSmb(String old, String newDir) {
try {
File copyfile = new File(old);
SmbFile temp_dir = new SmbFile(newDir);
if (copyfile.isFile()) {
SmbFile cp_smbfile = new SmbFile(newDir + copyfile.getName());
if (!cp_smbfile.exists())
cp_smbfile.createNewFile();
cp_smbfile.connect();
InputStream in = new FileInputStream(copyfile);
SmbFileOutputStream sfos = new SmbFileOutputStream(cp_smbfile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
sfos.write(buf, 0, len);
}
in.close();
sfos.close();
} else if (copyfile.isDirectory()) {
String files[] = copyfile.list();
// get dir name
String old_f = old.substring(old.lastIndexOf("/"), old.length());
int len = files.length;
SmbFile smbdir = new SmbFile(newDir + old_f.substring(1));
// create new directory
if (!smbdir.exists()) {
smbdir.mkdirs();
//return -1;
}
for (int i = 0; i <= len; i++) {
copySdToSmb(old + "/" + files[i], smbdir + "/");
}
} else if (!temp_dir.canWrite()) {
return -1;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
}
return 0;
}

convert "JSON data to textview" to "JSON data to listview"

Hello i have a working code that displays a twitter timeline into a textview:
void examineJSONdata()
{
TextView tvData = (TextView) findViewById(R.id.txtData);
try
{
String x = "";
InputStream is = this.getResources().openRawResource(R.raw.jsontwitter);
byte [] buffer = new byte[is.available()];
while (is.read(buffer) != -1);
String jsontext = new String(buffer);
JSONArray entries = new JSONArray(jsontext);
x = "JSON parsed.\nThere are [" + entries.length() + "]\n\n";
int i;
for (i=0;i<entries.length();i++)
{
JSONObject post = entries.getJSONObject(i);
x += "------------\n";
x += "Date:" + post.getString("created_at") + "\n";
x += "Post:" + post.getString("text") + "\n\n";
}
tvData.setText(x);
}
catch (Exception je)
{
tvData.setText("Error w/file: " + je.getMessage());
}
}
Now i want to try a ListView instead of a TextView
I have found a code on StackOverFlow Android App: JSON array from web to listview
ListView list = (ListView) findViewById(...);
String json = "[\"Country1\",\"Country2\",\"Country3\"]";
try {
JSONArray array = (JSONArray) new JSONTokener(json).nextValue();
String[] stringarray = new String[array.length()];
for (int i = 0; i < array.length(); i++) {
stringarray[i] = array.getString(i);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringarray);
list.setAdapter(adapter);
} catch (JSONException e) {
// handle JSON parsing exceptions...
}
I have tried to do this but I can't get i work
Would someone help convert the code with me? I think all the neccessary info is in the first code.
String x = "";
InputStream is = this.getResources().openRawResource(R.raw.jsontwitter);
byte [] buffer = new byte[is.available()];
while (is.read(buffer) != -1);
String jsontext = new String(buffer);
JSONArray array = new JSONArray(jsontext);
String[] stringarray = new String[array.length()];
and
int i;
for (i=0;i<array.length();i++)
{
JSONObject post = array.getJSONObject(i);
String temp;
temp += "Date:" + post.getString("created_at") + "\n";
temp += "Post:" + post.getString("text");
stringarray[i]=temp;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringarray);
list.setAdapter(adapter);

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);

I'm not understanding the following code

I have to understand this code to create my own app(almost based on this function):
public static String[][] ReadFilePerLine(Context context, String nom) {
int i = 0;
try {
FileInputStream fIn = context.openFileInput(nom);
InputStreamReader ipsr = new InputStreamReader(fIn);
BufferedReader b = new BufferedReader(ipsr);
i = getLineNumber(context, nom);
String[][] s = new String[2][i/2];
i = 0;
String ligne;
int j = 0;
while ((ligne = b.readLine()) != null) {
if (i % 2 == 0)
s[0][j] = ligne;
else {
s[1][j] = ligne;
j++;
}
i++;
}
fIn.close();
ipsr.close();
return s;
}
catch (Exception e)
{}
I'm not understanding why the using of a 2D array? and with two rows ?(String[][] s = new String[2][i/2];)
here is the data that it will be stored in the file:
data = date + " : " + y + "L/100KM"+ " " + value1 + "L "+ value2 + "KM\n";
Necessary functions:
public void updatelv(Activity activity) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String fileName = getResources().getString(R.string.fileName);
fileDir = "" + preferences.getString("login", "") + "."+ preferences.getString("marque", "") + ".";
s = myIO.ReadFilePerLine(getApplicationContext(), fileDir+fileName);
ListView L = (ListView) findViewById(R.id.lv);
L.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, s[0]));
for (int i = 0; i< s[0].length; i++) {
Log.d("Saves",s[0][i]);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.histo);
context = getApplicationContext();
activity = this;
final SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(context);
String fileName = getResources().getString(R.string.fileName);
fileDir = "" + preferences.getString("login", "") + "."+ preferences.getString("marque", "") + ".";
s = myIO.ReadFilePerLine(getApplicationContext(), fileDir + fileName);
updatelv(this);
ListView L = (ListView) findViewById(R.id.lv);
L.setTextFilterEnabled(true);
L.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
String tmp = s[1][position];
if (tmp == null)
tmp = "Aucun fichier trouvé!";
Toast.makeText(getApplicationContext(), tmp, Toast.LENGTH_SHORT)
.show();
}
});
ReadFilePerLine function:
public static String[][] ReadFilePerLine(Context context, String nom) {
int i = 0;
try {
FileInputStream fIn = context.openFileInput(nom);
InputStreamReader ipsr = new InputStreamReader(fIn);
BufferedReader b = new BufferedReader(ipsr);
i = getLineNumber(context, nom);
String[][] s = new String[2][i/2];
i = 0;
String ligne;
int j = 0;
while ((ligne = b.readLine()) != null) {
if (i % 2 == 0)
s[0][j] = ligne;
else {
s[1][j] = ligne;
j++;
}
i++;
}
fIn.close();
ipsr.close();
return s;
}
catch (Exception e)
{
}
Thank you for you help.
The code is clearly reading from a file whose format consists of pairs of lines; it puts the first line of each pair in s[0][...] and the second line of each pair in s[1][...]. If your format doesn't have that peculiarity -- which it doesn't sound as if it does -- then you don't need to do that. Just make an ordinary 1-dimensional array of Strings.
It appears that what they are doing is breaking the file down into two lists (or String arrays, in this case), one which contains all the even-numbered lines, and one which contains all the odd-numbered lines. I'll comment up the code for you:
public static String[][] ReadFilePerLine(Context context, String nom) {
int i = 0;
try {
//open the specified input file and create a reader
FileInputStream fIn = context.openFileInput(nom);
InputStreamReader ipsr = new InputStreamReader(fIn);
BufferedReader b = new BufferedReader(ipsr);
//get the total number of lines in the file, and allocate
//a buffer large enough to hold them all
i = getLineNumber(context, nom);
String[][] s = new String[2][i/2];
i = 0; //set the current line to 0
String ligne;
int j = 0; //set the section index to 0
//now read through the lines in the file, and place every
//even-numbered line in the first section ('s[0]'), and every
//odd-numbered line in the second section ('s[1]')
while ((ligne = b.readLine()) != null) {
if (i % 2 == 0)
//even-numbered line, it goes into the first section
s[0][j] = ligne;
else {
//odd-numbered line, it goes into the second section
s[1][j] = ligne;
j++; //increment the section index
}
i++; //increment the line count
}
//done, cleanup and return
fIn.close();
ipsr.close();
return s;
}
catch (Exception e) {
//should at least log an error here...
}
}
As to why they chose to use a String[][], I cannot say. Probably for convenience, since they want a single object that they can return from this function that contains both lists. Personally I would use a Map that has two List instances in it, but the String[][] works just as well and is probably marginally more efficient.
Judging from your example data it does not appear that you need to use this format. But if you want to use it, you need to structure your data so that the key is on one line, and its associated value is on the next, like:
date
2011-03-19
userName
someGuy
it seems to read from a file, split it into the two dimensional array (based on row count).
Why it does it? I have no idea why you'd want that. Check out the function that it returns s to and find out!

Categories

Resources