How to retrieve varbinary(max) image from SQL Server in android? - android

I am developing an android application in which I want to retrieve the image stored in SQL server database as shown in screenshot:
I have written a code for that but application will only retrieve the title column value and successfully shows in textview but in imageview nothing displays.Every kind of help is appreciated. Below is my code for that:
public class Menu_listen extends Fragment implements View.OnClickListener {
Connection con;
TextView t;
ImageView img;
String un,pass,db,ip,in;
private String abc;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("abc");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View InputFragmentView = inflater.inflate(R.layout.menu_1, container, false);
t = (TextView) InputFragmentView.findViewById(R.id.track_title);
img=(ImageView) InputFragmentView.findViewById(R.id.track_image);
ip = "192.168.***.**";
in="SQLEXPRESS";
db = "Testaudio";
un = "**";
pass = "****";
Check check1 = new Check();// this is the Asynctask, which is used to process in background to reduce load on app process
check1.execute("");
return InputFragmentView;
}
public String getAbc() {
return abc;
}
public void setAbc(String abc) {
this.abc = abc;
}
public class Check extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
#Override
protected void onPreExecute()
{
}
#Override
protected void onPostExecute(String r)
{
if(isSuccess)
{
Toast.makeText(getActivity() , "Successfull" , Toast.LENGTH_SHORT).show();
t.setText(getAbc());
byte[] decodeString = Base64.decode(r, Base64.DEFAULT);
Bitmap decodebitmap = BitmapFactory.decodeByteArray(decodeString, 0, decodeString.length);
img.setImageBitmap(decodebitmap);
}
}
#Override
protected String doInBackground(String... params)
{
try
{
con = connectionclass(un, pass, db, ip,in);
if (con == null)
{
z = "Check Your Internet Access!";
}
else
{
String query = "select * from getImg";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs != null && rs.next())
{
z = "successful";
isSuccess=true;
setAbc(rs.getString(3));
z=rs.getString(2);
}
con.close();
}
}
catch (Exception ex)
{
isSuccess = false;
z = ex.getMessage();
}
return z;
}
}
#SuppressLint("NewApi")
public Connection connectionclass(String user, String password, String database, String server,String instance) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://" + server + "/" + database + ";instance=" + instance + ";user=" + user + ";password=" + password + ";";
connection = DriverManager.getConnection(ConnectionURL);
} catch (SQLException se) {
Log.e("error here 1 : ", se.getMessage());
t.setText(se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("error here 2 : ", e.getMessage());
t.setText(e.getMessage());
} catch (Exception e) {
Log.e("error here 3 : ", e.getMessage());
t.setText(e.getMessage());
}
return connection;
}
}

Here the code i used for my app
This code will take a image from url and convert is to a byte array
byte[] logoImage = getLogoImage(IMAGEURL);
private byte[] getLogoImage(String url){
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
return baf.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
To save the image to db i used this code.
public void insertUser(){
SQLiteDatabase db = dbHelper.getWritableDatabase();
String delSql = "DELETE FROM ACCOUNTS";
SQLiteStatement delStmt = db.compileStatement(delSql);
delStmt.execute();
String sql = "INSERT INTO ACCOUNTS (account_id,account_name,account_image) VALUES(?,?,?)";
SQLiteStatement insertStmt = db.compileStatement(sql);
insertStmt.clearBindings();
insertStmt.bindString(1, Integer.toString(this.accId));
insertStmt.bindString(2,this.accName);
insertStmt.bindBlob(3, this.accImage);
insertStmt.executeInsert();
db.close();
}
To retrieve the image back this is code i used.
public Account getCurrentAccount() {
SQLiteDatabase db = dbHelper.getWritableDatabase();
String sql = "SELECT * FROM ACCOUNTS";
Cursor cursor = db.rawQuery(sql, new String[] {});
if(cursor.moveToFirst()){
this.accId = cursor.getInt(0);
this.accName = cursor.getString(1);
this.accImage = cursor.getBlob(2);
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
db.close();
if(cursor.getCount() == 0){
return null;
} else {
return this;
}
}
Finally to load this image to a imageview
logoImage.setImageBitmap(BitmapFactory.decodeByteArray( currentAccount.accImage,
0,currentAccount.accImage.length));

Related

Access to google calendar events

I want to get the events from a public google calendar in my app.
This is my activity, with the access to somePublicCalendar#google.com which I've changed for a fake account, but my calendar is public. Of course, somePublicCalendar#gmail.com is not my account and I can't manage it. Just want to see if I there's a gap for scheduling and appointment.
This is my activity, and for the moment, the cursor seems to be empty.
public class calendar extends AppCompatActivity implements View.OnClickListener{
CalendarView calendarView;
final int callbackId = 42;
Button home;
// Projection array. Creating indices for this array instead of doing
// dynamic lookups improves performance.
public static final String[] EVENT_PROJECTION = new String[] {
CalendarContract.Calendars._ID, // 0
CalendarContract.Calendars.ACCOUNT_NAME, // 1
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, // 2
CalendarContract.Calendars.OWNER_ACCOUNT // 3
};
// The indices for the projection array above.
private static final int PROJECTION_ID_INDEX = 0;
private static final int PROJECTION_ACCOUNT_NAME_INDEX = 1;
private static final int PROJECTION_DISPLAY_NAME_INDEX = 2;
private static final int PROJECTION_OWNER_ACCOUNT_INDEX = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
home = findViewById(R.id.inicio);
calendarView = findViewById(R.id.calendarView);
checkPermission(callbackId, Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR);
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(#NonNull CalendarView view, int year, int month, int dayOfMonth) {
consultarCalendario();
}
});
}
#Override
public void onRequestPermissionsResult(int callbackId,
String permissions[], int[] grantResults) {
}
public void consultarCalendario() {
// Run query
Cursor cur = null;
ContentResolver cr = getContentResolver();
Uri uri = CalendarContract.Calendars.CONTENT_URI;
String selection = "((" + CalendarContract.Calendars.ACCOUNT_NAME + " = ?) AND ("
+ CalendarContract.Calendars.ACCOUNT_TYPE + " = ?) AND ("
+ CalendarContract.Calendars.OWNER_ACCOUNT + " = ?))";
String[] selectionArgs = new String[]{"somePublicCalendar#gmail.com", "com.google",
"somePublicCalendar#gmail.com"};
// Submit the query and get a Cursor object back.
cur = cr.query(uri, EVENT_PROJECTION, selection, selectionArgs, null);
// Use the cursor to step through the returned records
while (cur.moveToNext()) {
long calID = 0;
String displayName = null;
String accountName = null;
String ownerName = null;
// Get the field values
calID = cur.getLong(PROJECTION_ID_INDEX);
displayName = cur.getString(PROJECTION_DISPLAY_NAME_INDEX);
accountName = cur.getString(PROJECTION_ACCOUNT_NAME_INDEX);
ownerName = cur.getString(PROJECTION_OWNER_ACCOUNT_INDEX);
// Do something with the values...
Log.d("Conexion a calendario",calID + "/" + displayName+ "/" + accountName + "/" + ownerName);
}
}
private void checkPermission(int callbackId, String... permissionsId) {
boolean permissions = true;
for (String p : permissionsId) {
permissions = permissions && ContextCompat.checkSelfPermission(this, p) == PERMISSION_GRANTED;
}
if (!permissions)
ActivityCompat.requestPermissions(this, permissionsId, callbackId);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.inicio:
startActivity(new Intent(this, Principal.class));
break;
}
}
}
I'm not familiar with the Calendar libraries you are using, but this is how I got entries from a Google Calendar:
private void callGetEvents() {
String sURL1 = "https://www.googleapis.com/calendar/v3/calendars/somePublicCalendar%40gmail.com/events?key=XYZTHECALENDARKEYZYX";
getEvents(sURL1);
}
private void getEvents(String url) {
final ProgressDialog dialog;
dialog = new ProgressDialog(thisContext);
dialog.setMessage((String) getResources().getText(R.string.loading_please_wait));
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
listOfEvents = new ArrayList<EventItem>();
JsonObjectRequest req = new JsonObjectRequest(url, null, new Response.Listener<JSONObject> () {
#SuppressLint("SimpleDateFormat")
#Override
public void onResponse(JSONObject response) {
try {
JSONArray items = response.getJSONArray("items");
Date today = new Date();
for (int i = 0; i < items.length(); i++) {
JSONObject oneObject = null;
try {
oneObject = items.getJSONObject(i);
} catch (JSONException e) {
continue;
}
String title = "";
try {
title = oneObject.getString("summary");
} catch (JSONException e) {
title = "";
}
String description = "";
try {
description = oneObject.getString("description");
} catch (JSONException e) {
description = "";
}
String location = "";
try {
location = oneObject.getString("location");
} catch (JSONException e) {
location = "";
}
JSONObject startObject = null;
String startDate = "";
Date start_date = new Date();
JSONObject endObject = null;
String endDate = "";
Date end_date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
try {
startObject = oneObject.getJSONObject("start");
startDate = startObject.getString("dateTime");
try {
start_date = dateFormat.parse(startDate);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
endObject = oneObject.getJSONObject("end");
endDate = endObject.getString("dateTime");
try {
end_date = dateFormat.parse(endDate);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
EventItem item = new EventItem(title, description, location, start_date, end_date);
Log.i("Compare", today.toString() + ":" + endDate);
if (title.length() > 0) {
if (today.compareTo(end_date) < 0) {
listOfEvents.add(item);
}
}
}
Collections.sort(listOfEvents, new Comparator<EventItem>() {
public int compare(EventItem o1, EventItem o2) {
return o1.getStartDate().compareTo(o2.getStartDate());
}
});
try {
adapter = new EventListAdapter(thisContext, listOfEvents);
eventListView.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
dialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
Log.e("Error: ", error.getMessage());
dialog.dismiss();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json; charset=UTF-8");
headers.put("Content-Type", "application/json; charset=UTF-8");
return headers;
};
};
// add the request object to the queue to be executed
MyApplication.getInstance().addToRequestQueue(req);
}

Android: unable to zip generated files

I'm working on this project where I generated CSV files from contact list, and now I'm supposed to package all the files as a single zip archive using RxJava, so I'm trying to get the method to create an archive invoked using onComplete method. But the application is crashing with this error:
Attempt to invoke direct method 'boolean appjoe.wordpress.com.testdemo.Tab2$FileHelper.zip(java.lang.String, java.lang.String)' on a null object reference
This is my code:
path: /storage/emulated/0/Android/data/com.wordpress.appjoe/csv
File location = new File(Environment.getExternalStorageDirectory(), "Android/data/com.wordpress.appjoe/csv/");
File fileLocation;
FileOutputStream dest;
String path;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_tab2, container, false);
mbutton = v.findViewById(R.id.extractContact);
mbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Permission has already been granted
Observer observer = new Observer() {
#Override
public void onSubscribe(Disposable d) {
mCursor = getCursor();
fCursor = getCursor();
location.mkdirs();
path = location.getAbsolutePath();
try {
dest = new FileOutputStream(path);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
#Override
public void onNext(Object o) {
contactData = o.toString();
fCursor.moveToPosition(count);
fileLocation = new File(path, getName(fCursor)+".csv");
try {
FileOutputStream fileOut = new FileOutputStream(fileLocation);
fileOut.write(contactData.getBytes());
fileOut.flush();
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
mCursor.close();
fCursor.close();
// Creating archive once the CSV files are generated
if (fileHelper.zip(path, location.getParent())) {
Toast.makeText(getContext(), "Zip successful", Toast.LENGTH_SHORT).show();
}
Log.d("fileLocation", "location: " + location.getParent());
Log.d("fileLocation", "path: " + path);
Log.d("Observer_contact", "Completed");
}
};
io.reactivex.Observable.create(new ObservableOnSubscribe<String>() {
#Override
public void subscribe(ObservableEmitter<String> emitter) throws Exception {
try {
for (count = 0; count < mCursor.getCount(); count++) {
emitter.onNext(loadContacts(count));
}
emitter.onComplete();
} catch (Exception e) {
emitter.onError(e);
}
}
}).subscribeOn(Schedulers.io())
.distinct()
.subscribeWith(observer);
}
}
});
// Inflate the layout for this fragment
return v;
}
RxJava implementation to fetch contacts:
public String loadContacts(int i) {
StringBuilder mBuilder = new StringBuilder();
ContentResolver mContentResolver = getActivity().getContentResolver();
mCursor.moveToPosition(i);
if (mCursor.getCount() > 0 ) {
String id = getID(mCursor);
String name = getName(mCursor);
int hasPhoneNumber = hasNumber(mCursor);
if (hasPhoneNumber > 0) {
mBuilder.append("\"").append(name).append("\"");
Cursor cursor = mContentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "= ?",
new String[]{id}, null);
assert cursor != null;
while (cursor.moveToNext()) {
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
.replaceAll("\\s", "");
// if number is not existing in the list, then add number to the string
if (!(mBuilder.toString().contains(phoneNumber))) {
mBuilder.append(", ").append(phoneNumber);
}
}
cursor.close();
}
}
return mBuilder.toString();
}
Methods to get necessary information:
private Cursor getCursor() {
ContentResolver mContentResolver = getActivity().getContentResolver();
return mContentResolver.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " ASC");
}
private String getID(Cursor cursor) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
return id;
}
private String getName(Cursor cursor) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
return name;
}
private int hasNumber(Cursor cursor) {
return Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
}
Class to generate archive
// Custom class to help with zipping of generated CSVs
private class FileHelper {
private static final int BUFFER_SIZE = 2048;
private String TAG = FileHelper.class.getName();
private String parentPath = "";
private String destinationFileName = "Contacts_CSV.zip";
private boolean zip (String sourcePath, String destinationPath) {
new File(destinationPath).mkdirs();
FileOutputStream fileOutputStream;
ZipOutputStream zipOutputStream = null;
try {
if (!destinationPath.endsWith("/")) {
destinationPath = destinationPath + "/";
}
String destination = destinationPath + destinationFileName;
File file = new File(destination);
if (!file.exists()) {
file.createNewFile();
}
fileOutputStream = new FileOutputStream(file);
zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream));
parentPath = new File(sourcePath).getParent() + "/";
zipFile(zipOutputStream, sourcePath);
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG,e.getMessage());
return false;
} finally {
if (zipOutputStream!=null)
try {
zipOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
private void zipFile (ZipOutputStream zipOutputStream, String sourcePath) throws IOException {
java.io.File files = new java.io.File(sourcePath);
java.io.File[] fileList = files.listFiles();
String entryPath="";
BufferedInputStream input;
for (java.io.File file : fileList) {
if (file.isDirectory()) {
} else {
byte data[] = new byte[BUFFER_SIZE];
FileInputStream fileInputStream = new FileInputStream(file.getPath());
input = new BufferedInputStream(fileInputStream, BUFFER_SIZE);
entryPath = file.getAbsolutePath().replace(parentPath, "");
ZipEntry entry = new ZipEntry(entryPath);
zipOutputStream.putNextEntry(entry);
int count;
while ((count = input.read(data, 0, BUFFER_SIZE)) != -1) {
zipOutputStream.write(data, 0, count);
}
input.close();
}
}
}
}
I solved this problem by removing the class FileHelper and making both the methods inside FileHelper private methods within the main class. That way, calling the methods from onComplete() didn't cause the program to crash, and it was successfully generating the zip file.

exception when trying to update records in the database

what i am trying to do is updating the records where it will search for the itemnumber and use is id to change the shelfnumber in another table based on what is in the edittext
this is the error i get when i tries to update the record
java.sql.SQLException: Incorrect syntax near the keyword 'file'.
and that happends at my public class and on my preparedStatement.executeUpdate();
public class UpdatePro extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
String item = cardnumberbox.getText().toString();
String shelf = shelfnumberbox.getText().toString();
#Override
protected String doInBackground(String... params) {
if (item.trim().equals("") || shelf.trim().equals(""))
z = getString(R.string.Invalid_Credentials);
else {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = getString(R.string.Forbindelses_fejl);;
} else {
String text1 = item;
{
if(text1.substring(0,1).startsWith("K"))
{
text1 = text1.substring(1);
}
else
{
text1= text1 ;//.substring(0));
}
}
String text2 = shelf;
{
if(text2.substring(0,1).startsWith("R"))
{
text2 = text2.substring(1);
}
else
{
text2= text2 ;//.substring(0));
}
}
String query = "Update PS set ShelfNumber = "+text2+ " from file.ItemPart PS "+ " join file.item P on P.id = PS.id "+ " where P.ItemNumber = '"+text1 + "'";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
z = getString(R.string.Update_succes);
isSuccess = true;
}
} catch (Exception ex) {
isSuccess = false;
Log.e("YOUR_APP_LOG_TAG", "I got an error", ex);
z = getString(R.string.Exceptions);
}
}
return z;
Try :
public class UpdatePro extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
String item = cardnumberbox.getText().toString();
String shelf = shelfnumberbox.getText().toString();
#Override
protected String doInBackground(String... params) {
if (item.trim().equals("") || shelf.trim().equals(""))
z = getString(R.string.Invalid_Credentials);
else {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = getString(R.string.Forbindelses_fejl);;
} else {
String text1 = item;
{
if(text1.substring(0,1).startsWith("K"))
{
text1 = text1.substring(1);
}
else
{
text1= text1 ;//.substring(0));
}
}
String text2 = shelf;
{
if(text2.substring(0,1).startsWith("R"))
{
text2 = text2.substring(1);
}
else
{
text2= text2 ;//.substring(0));
}
}
String query = "Update PS set ShelfNumber = "+text2+ " from [file].[ItemPart] PS "+ " join [file].[item] P on P.id = PS.id "+ " where P.ItemNumber = '"+text1 + "'";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
z = getString(R.string.Update_succes);
isSuccess = true;
}
} catch (Exception ex) {
isSuccess = false;
Log.e("YOUR_APP_LOG_TAG", "I got an error", ex);
z = getString(R.string.Exceptions);
}
}
return z;

Saving/Storeing an external image into SQLite Database

I have a book-App, where I scan a book with barcodescanner and retrieving the information from googlebooksapi.
At the moment I can save the general bookinfos, title, author, date, rating and shelf (where i want to display the book) in my SQLite database
Now I want to save the bookcover, which comes with the googleapi, too.
Can you tell me how I can save the image in my SQlite Database. By looking for solution I realized that I have to blob the image. but I dont know how.
Following my activties.
ScanActivity.java -> at the end of the code, I save the book data into sql db
public class ScanActivity extends AppCompatActivity implements OnClickListener {
private Button scanBtn, previewBtn, linkBtn, addBookBtn, librarybtn;
public TextView authorText, titleText, descriptionText, dateText, ratingCountText;
public EditText shelfText;
private LinearLayout starLayout;
private ImageView thumbView;
private ImageView[] starViews;
private Bitmap thumbImg;
public BookDBHelper bookDBHelper;
public SQLiteDatabase sqLiteDatabase1;
public Context context1 = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
//Fonts
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
Button myButtonViewScan = (Button) findViewById(R.id.scan_button);
myButtonViewScan.setTypeface(myTypeface);
TextView myWheretoSaveTextView = (TextView) findViewById(R.id.textView_wheretosave);
myWheretoSaveTextView.setTypeface(myTypeface);
//Scanbutton
scanBtn = (Button) findViewById(R.id.scan_button);
scanBtn.setOnClickListener(this);
//Preview Button
previewBtn = (Button) findViewById(R.id.preview_btn);
previewBtn.setVisibility(View.GONE);
previewBtn.setOnClickListener(this);
//Weblink Button
linkBtn = (Button) findViewById(R.id.link_btn);
linkBtn.setVisibility(View.GONE);
linkBtn.setOnClickListener(this);
/* //AddBookBtn
addBookBtn= (Button)findViewById(R.id.btn_savebook);
addBookBtn.setVisibility(View.GONE);
addBookBtn.setOnClickListener(this);
//LibraryButton
librarybtn = (Button) findViewById(R.id.btn_maps);
librarybtn.setVisibility(View.GONE);
librarybtn.setOnClickListener(this);
*/
authorText = (TextView) findViewById(R.id.book_author);
titleText = (TextView) findViewById(R.id.book_title);
descriptionText = (TextView) findViewById(R.id.book_description);
dateText = (TextView) findViewById(R.id.book_date);
starLayout = (LinearLayout) findViewById(R.id.star_layout);
ratingCountText = (TextView) findViewById(R.id.book_rating_count);
thumbView = (ImageView) findViewById(R.id.thumb);
shelfText = (EditText) findViewById(R.id.editText_wheretosave);
starViews = new ImageView[5];
for (int s = 0; s < starViews.length; s++) {
starViews[s] = new ImageView(this);
}
starViews = new ImageView[5];
for (int s = 0; s < starViews.length; s++) {
starViews[s] = new ImageView(this);
}
}
public void onClick(View v) {
if (v.getId() == R.id.scan_button) {
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
} else if (v.getId() == R.id.link_btn) {
//get the url tag
String tag = (String) v.getTag();
//launch the url
Intent webIntent = new Intent(Intent.ACTION_VIEW);
webIntent.setData(Uri.parse(tag));
startActivity(webIntent);
} else if (v.getId() == R.id.preview_btn) {
String tag = (String) v.getTag();
Intent intent = new Intent(this, EmbeddedBook.class);
intent.putExtra("isbn", tag);
startActivity(intent);
//launch preview
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve result of scanning - instantiate ZXing object
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
//check we have a valid result
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
//get format name of data scanned
String scanFormat = scanningResult.getFormatName();
previewBtn.setTag(scanContent);
if (scanContent != null && scanFormat != null && scanFormat.equalsIgnoreCase("EAN_13")) {
String bookSearchString = "https://www.googleapis.com/books/v1/volumes?" +
"q=isbn:" + scanContent + "&key=AIzaSyDminlOe8YitHijWd51n7-w2h8W1qb5PP0";
new GetBookInfo().execute(bookSearchString);
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"Not a valid scan!", Toast.LENGTH_SHORT);
toast.show();
}
Log.v("SCAN", "content: " + scanContent + " - format: " + scanFormat);
} else {
//invalid scan data or scan canceled
Toast toast = Toast.makeText(getApplicationContext(),
"No book scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
private class GetBookInfo extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... bookURLs) {
StringBuilder bookBuilder = new StringBuilder();
for (String bookSearchURL : bookURLs) {
HttpClient bookClient = new DefaultHttpClient();
try {
HttpGet bookGet = new HttpGet(bookSearchURL);
HttpResponse bookResponse = bookClient.execute(bookGet);
StatusLine bookSearchStatus = bookResponse.getStatusLine();
if (bookSearchStatus.getStatusCode() == 200) {
HttpEntity bookEntity = bookResponse.getEntity();
InputStream bookContent = bookEntity.getContent();
InputStreamReader bookInput = new InputStreamReader(bookContent);
BufferedReader bookReader = new BufferedReader(bookInput);
String lineIn;
while ((lineIn = bookReader.readLine()) != null) {
bookBuilder.append(lineIn);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return bookBuilder.toString();
}
protected void onPostExecute(String result) {
try {
previewBtn.setVisibility(View.VISIBLE);
JSONObject resultObject = new JSONObject(result);
JSONArray bookArray = resultObject.getJSONArray("items");
JSONObject bookObject = bookArray.getJSONObject(0);
JSONObject volumeObject = bookObject.getJSONObject("volumeInfo");
try {
titleText.setText(volumeObject.getString("title"));
} catch (JSONException jse) {
titleText.setText("");
jse.printStackTrace();
}
StringBuilder authorBuild = new StringBuilder("");
try {
JSONArray authorArray = volumeObject.getJSONArray("authors");
for (int a = 0; a < authorArray.length(); a++) {
if (a > 0) authorBuild.append(", ");
authorBuild.append(authorArray.getString(a));
}
authorText.setText(authorBuild.toString());
} catch (JSONException jse) {
authorText.setText("");
jse.printStackTrace();
}
try {
dateText.setText(volumeObject.getString("publishedDate"));
} catch (JSONException jse) {
dateText.setText("");
jse.printStackTrace();
}
try {
descriptionText.setText("DESCRIPTION: " + volumeObject.getString("description"));
} catch (JSONException jse) {
descriptionText.setText("");
jse.printStackTrace();
}
try {
double decNumStars = Double.parseDouble(volumeObject.getString("averageRating"));
int numStars = (int) decNumStars;
starLayout.setTag(numStars);
starLayout.removeAllViews();
for (int s = 0; s < numStars; s++) {
starViews[s].setImageResource(R.drawable.star);
starLayout.addView(starViews[s]);
}
} catch (JSONException jse) {
starLayout.removeAllViews();
jse.printStackTrace();
}
try {
ratingCountText.setText(volumeObject.getString("ratingsCount") + " ratings");
} catch (JSONException jse) {
ratingCountText.setText("");
jse.printStackTrace();
}
try {
boolean isEmbeddable = Boolean.parseBoolean
(bookObject.getJSONObject("accessInfo").getString("embeddable"));
if (isEmbeddable) previewBtn.setEnabled(true);
else previewBtn.setEnabled(false);
} catch (JSONException jse) {
previewBtn.setEnabled(false);
jse.printStackTrace();
}
try {
linkBtn.setTag(volumeObject.getString("infoLink"));
linkBtn.setVisibility(View.VISIBLE);
} catch (JSONException jse) {
linkBtn.setVisibility(View.GONE);
jse.printStackTrace();
}
try {
JSONObject imageInfo = volumeObject.getJSONObject("imageLinks");
new GetBookThumb().execute(imageInfo.getString("smallThumbnail"));
} catch (JSONException jse) {
thumbView.setImageBitmap(null);
jse.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
titleText.setText("NOT FOUND");
authorText.setText("");
descriptionText.setText("");
dateText.setText("");
starLayout.removeAllViews();
ratingCountText.setText("");
thumbView.setImageBitmap(null);
previewBtn.setVisibility(View.GONE);
shelfText.setText("");
}
}
}
private class GetBookThumb extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... thumbURLs) {
try {
URL thumbURL = new URL(thumbURLs[0]);
URLConnection thumbConn = thumbURL.openConnection();
thumbConn.connect();
InputStream thumbIn = thumbConn.getInputStream();
BufferedInputStream thumbBuff = new BufferedInputStream(thumbIn);
thumbImg = BitmapFactory.decodeStream(thumbBuff);
thumbBuff.close();
thumbIn.close();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
protected void onPostExecute(String result) {
thumbView.setImageBitmap(thumbImg);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void showMaps(View view) {
Intent intent = new Intent(this, MapsActivity.class);
startActivity(intent);
}
//HERE I SAVE THE RETRIEVED DATA
public void saveBook(View view) { //Click on save Book
String title = titleText.getText().toString();
String author = authorText.getText().toString();
String date = dateText.getText().toString();
String rating = ratingCountText.getText().toString();
String shelf = shelfText.getText().toString();
bookDBHelper = new BookDBHelper(context1);
sqLiteDatabase1 = bookDBHelper.getWritableDatabase();
bookDBHelper.addInformations(title, author, date, rating, shelf, sqLiteDatabase1);
Toast.makeText(getBaseContext(), "Data Saved", Toast.LENGTH_LONG).show();
bookDBHelper.close();
}
}
BookDBHelper.java
public class BookDBHelper extends SQLiteOpenHelper{
private static final String DATABASE_BOOKS_NAME = "BookINFO.DB";
private static final int DATABASE_BOOKS_VERS = 2;
private static final String CREATE_QUERY_BOOKS =
"CREATE TABLE "
+ BookContent.NewBookInfo.TABLE_NAME_BOOKS
+"("
+ BookContent.NewBookInfo.BOOK_ID + "INTEGER PRIMARY KEY, "
+ BookContent.NewBookInfo.BOOK_IMAGE +" BLOB, "
+ BookContent.NewBookInfo.BOOK_IMAGE_TAG +" TEXT, "
+ BookContent.NewBookInfo.BOOK_TITLE+" TEXT, "
+ BookContent.NewBookInfo.BOOK_AUTHOR+" TEXT, "
+ BookContent.NewBookInfo.BOOK_DATE+" TEXT, "
+ BookContent.NewBookInfo.BOOK_RATING+" TEXT, "
+ BookContent.NewBookInfo.BOOK_SHELF+" TEXT);";
public BookDBHelper(Context context){
super(context, DATABASE_BOOKS_NAME, null, DATABASE_BOOKS_VERS);
Log.e("DATABASE OPERATIONS", " DATABASE CREATED");
}
#Override
public void onCreate(SQLiteDatabase bookdb) {
bookdb.execSQL(CREATE_QUERY_BOOKS);
Log.e("DATABASE OPERATIONS", " DATABASE CREATED");
}
#Override
public void onUpgrade(SQLiteDatabase bookdb, int oldVersion, int newVersion) {
bookdb.execSQL(" DROP TABLE IS EXISTS " + BookContent.NewBookInfo.TABLE_NAME_BOOKS);
onCreate(bookdb);
}
public void addInformations( String booktitle, String bookauthor, String bookdate, String bookrating, String bookshelf, SQLiteDatabase bookdb)
{
ContentValues contentValues = new ContentValues();
contentValues.put(BookContent.NewBookInfo.BOOK_TITLE, booktitle);
contentValues.put(BookContent.NewBookInfo.BOOK_AUTHOR, bookauthor);
contentValues.put(BookContent.NewBookInfo.BOOK_DATE, bookdate);
contentValues.put(BookContent.NewBookInfo.BOOK_RATING, bookrating);
contentValues.put(BookContent.NewBookInfo.BOOK_SHELF, bookshelf);
bookdb.insert(BookContent.NewBookInfo.TABLE_NAME_BOOKS, null, contentValues);
Log.e("DATABASE OPERATIONS", "ON ROW INSERTED");
}
public Cursor getInformations(SQLiteDatabase bookdb){
Cursor cursor2;
String[] projections = {
BookContent.NewBookInfo.BOOK_TITLE,
BookContent.NewBookInfo.BOOK_AUTHOR,
BookContent.NewBookInfo.BOOK_DATE,
BookContent.NewBookInfo.BOOK_RATING,
BookContent.NewBookInfo.BOOK_SHELF};
cursor2 = bookdb.query(BookContent.NewBookInfo.TABLE_NAME_BOOKS, projections,null, null, null, null, null);
return cursor2;
}
Afterwards the infos will be displayed in a liestview.
BookDataListActivity
public class BookDataListActivity extends Activity {
public ListView booklistView;
private EditText inputSearch = null;
public SQLiteDatabase sqLiteDatabaseBooks = null;
public BookDBHelper bookDBHelper;
public Cursor cursor2;
public BookListDataAdapter bookListDataAdapter;
public final static String EXTRA_MSG1 = "title";
public final static String EXTRA_MSG2 = "author";
public final static String EXTRA_MSG3 = "date";
public final static String EXTRA_MSG4 = "rating";
public final static String EXTRA_MSG5 = "shelf";
public TextView editTextBooktitle;
public TextView editTextBookauthor;
public TextView editTextBookdate;
public TextView editTextBookrating;
public TextView editTextBookshelf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.book_data_list_layout);
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
TextView myTextView = (TextView) findViewById(R.id.text_yourbooks);
myTextView.setTypeface(myTypeface);
booklistView = (ListView) findViewById(R.id.book_list_view);
inputSearch = (EditText) findViewById(R.id.search_bar);
bookListDataAdapter = new BookListDataAdapter(getApplicationContext(), R.layout.row_book_layout);
booklistView.setAdapter(bookListDataAdapter);
//onItemClickListener
booklistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), BookInfoActivity.class);
editTextBooktitle = (TextView) view.findViewById(R.id.text_book_title);
String book_title = editTextBooktitle.getText().toString();
intent.putExtra(EXTRA_MSG1, book_title);
editTextBookauthor = (TextView) view.findViewById(R.id.text_book_author);
String bookauthor = editTextBookauthor.getText().toString();
intent.putExtra(EXTRA_MSG2, bookauthor);
editTextBookdate = (TextView) view.findViewById(R.id.text_book_date);
String bookdate = editTextBookdate.getText().toString();
intent.putExtra(EXTRA_MSG3, bookdate);
editTextBookrating = (TextView) view.findViewById(R.id.text_book_rating);
String bookrating = editTextBookrating.getText().toString();
intent.putExtra(EXTRA_MSG4, bookrating);
editTextBookshelf = (TextView) view.findViewById(R.id.text_book_shelf);
String bookshelf = editTextBookshelf.getText().toString();
intent.putExtra(EXTRA_MSG5, bookshelf);
startActivity(intent);
}
});
bookDBHelper = new BookDBHelper(getApplicationContext());
sqLiteDatabaseBooks = bookDBHelper.getReadableDatabase();
cursor2 = bookDBHelper.getInformations(sqLiteDatabaseBooks);
if (cursor2.moveToFirst()) {
do {
String booktitle, bookauthor, bookdate, bookrating, bookshelf;
booktitle = cursor2.getString(0);
bookauthor = cursor2.getString(1);
bookdate = cursor2.getString(2);
bookrating = cursor2.getString(3);
bookshelf = cursor2.getString(4);
BookDataProvider bookDataProvider = new BookDataProvider(booktitle, bookauthor, bookdate, bookrating, bookshelf);
bookListDataAdapter.add(bookDataProvider);
} while (cursor2.moveToNext());
}
}
}
And I think you will need the DataAdapter
DataListDataAdapter
public class BookListDataAdapter extends ArrayAdapter implements Filterable{
List booklist = new ArrayList();
public SQLiteDatabase sqLiteDatabaseBooks;
public BookListDataAdapter(Context context,int resource) {
super(context, resource);
}
static class BookLayoutHandler {
TextView BOOKTITLE, BOOKAUTHOR, BOOKDATE, BOOKRATING, BOOKSHELF;
}
#Override
public void add (Object object){
super.add(object);
booklist.add(object);
}
#Override
public int getCount() {
return booklist.size();
}
#Override
public Object getItem(int position) {
return booklist.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row1= convertView;
BookLayoutHandler bookLayoutHandler;
if(row1 == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row1 = layoutInflater.inflate(R.layout.row_book_layout, parent, false);
bookLayoutHandler = new BookLayoutHandler();
bookLayoutHandler.BOOKTITLE = (TextView) row1.findViewById(R.id.text_book_title);
bookLayoutHandler.BOOKAUTHOR = (TextView) row1.findViewById(R.id.text_book_author);
bookLayoutHandler.BOOKDATE = (TextView) row1.findViewById(R.id.text_book_date);
bookLayoutHandler.BOOKRATING = (TextView) row1.findViewById(R.id.text_book_rating);
bookLayoutHandler.BOOKSHELF = (TextView) row1.findViewById(R.id.text_book_shelf);
row1.setTag(bookLayoutHandler);
}else{
bookLayoutHandler = (BookLayoutHandler) row1.getTag();
}
BookDataProvider bookDataProvider = (BookDataProvider) this.getItem(position);
bookLayoutHandler.BOOKTITLE.setText(bookDataProvider.getBooktitle());
bookLayoutHandler.BOOKAUTHOR.setText(bookDataProvider.getBookauthor());
bookLayoutHandler.BOOKDATE.setText(bookDataProvider.getBookdate());
bookLayoutHandler.BOOKRATING.setText(bookDataProvider.getBookrating());
bookLayoutHandler.BOOKSHELF.setText(bookDataProvider.getBookshelf());
return row1;
}
BookDataProvider:
public class BookDataProvider {
private Bitmap bookimage;
private String booktitle;
private String bookauthor;
private String bookdate;
private String bookrating;
private String bookshelf;
public Bitmap getBookimage() {
return bookimage;
}
public void setBookimage(Bitmap bookimage) {
this.bookimage = bookimage;
}
public String getBooktitle() {
return booktitle;
}
public void setBooktitle(String booktitle) {
this.booktitle = booktitle;
}
public String getBookauthor() {
return bookauthor;
}
public void setBookauthor(String bookauthor) {
this.bookauthor = bookauthor;
}
public String getBookdate() {
return bookdate;
}
public void setBookdate(String bookdate) {
this.bookdate = bookdate;
}
public String getBookrating() {
return bookrating;
}
public void setBookrating(String bookrating) {
this.bookrating = bookrating;
}
public String getBookshelf() {
return bookshelf;
}
public void setBookshelf(String bookshelf) {
this.bookshelf = bookshelf;
}
public BookDataProvider ( Bitmap bookimage, String booktitle, String bookauthor, String bookdate, String bookrating, String bookshelf)
{
this.bookimage = bookimage;
this.booktitle = booktitle;
this.bookauthor = bookauthor;
this.bookdate = bookdate;
this.bookrating = bookrating;
this.bookshelf = bookshelf;
}
}
BookContent
public class BookContent {
public static abstract class NewBookInfo{ //Tabllenspalten deklaration
public static final String BOOK_IMAGE = "book_image";
public static final String BOOK_IMAGE_TAG ="image_tag";
public static final String BOOK_TITLE = "book_title";
public static final String BOOK_AUTHOR = "book_author";
public static final String BOOK_DATE = "book_date";
public static final String BOOK_RATING = "book_rating";
public static final String BOOK_SHELF = "book_shelf";
public static final String TABLE_NAME_BOOKS = "book_info";
public static final String BOOK_ID = "_id";
}
}
If I get your question right, you need to convert your image to a blob.
Well, blob is a byte array, so the following code would help you to convert your Bitmap to a byte[]
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, thumbImg);
byte[] blob = stream.toByteArray();
You can also get the whole implementation from another question here:
how to store Image as blob in Sqlite & how to retrieve it?
EDIT:
Of course, you have to edit your BookDBHelper.addInformations function and add one additional parameter for your image:
public void addInformations( String booktitle, String bookauthor, String bookdate, String bookrating, String bookshelf, byte[] image, SQLiteDatabase bookdb)
{
ContentValues contentValues = new ContentValues();
contentValues.put(BookContent.NewBookInfo.BOOK_TITLE, booktitle);
contentValues.put(BookContent.NewBookInfo.BOOK_AUTHOR, bookauthor);
contentValues.put(BookContent.NewBookInfo.BOOK_DATE, bookdate);
contentValues.put(BookContent.NewBookInfo.BOOK_RATING, bookrating);
contentValues.put(BookContent.NewBookInfo.BOOK_SHELF, bookshelf);
contentValues.put(YOUR_IMAGE_CONSTANT, image);
bookdb.insert(BookContent.NewBookInfo.TABLE_NAME_BOOKS, null, contentValues);
Log.e("DATABASE OPERATIONS", "ON ROW INSERTED");
}
Now you can save your Book through ScanActivity.saveBook:
public void saveBook(View view) { //Click on save Book
// ...
BitmapDrawable bitmapDrawable = (BitmapDrawable) thumbView.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] blob = stream.toByteArray();
sqLiteDatabase1 = bookDBHelper.getWritableDatabase();
bookDBHelper.addInformations(title, author, date, rating, shelf, blob, sqLiteDatabase1);
Toast.makeText(getBaseContext(), "Data Saved", Toast.LENGTH_LONG).show();
bookDBHelper.close();
}

NullPointerException on getting data from database

I've made working source codes on synchronizing database before but suddenly it's not working now. Here, I'm trying to read my records in local database in the DB_User class. But it returned java.lang.NullPointerException. So this is what I made.
This is the stacktrace of my error
01-15 06:42:20.080: I/ActivityManager(60): Displayed activity com.yolanda.ta/.DBSynchronizer: 387 ms (total 387 ms)
01-15 06:42:40.639: D/dalvikvm(1147): GC_FOR_MALLOC freed 2008 objects / 125592 bytes in 74ms
01-15 06:43:21.149: D/dalvikvm(1147): GC_FOR_MALLOC freed 777 objects / 219464 bytes in 79ms
01-15 06:44:02.018: D/dalvikvm(1147): GC_FOR_MALLOC freed 830 objects / 404856 bytes in 67ms
01-15 06:44:35.578: D/dalvikvm(1147): GC_FOR_MALLOC freed 830 objects / 404976 bytes in 78ms
01-15 06:44:58.399: W/dalvikvm(1147): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
01-15 06:44:58.411: E/AndroidRuntime(1147): FATAL EXCEPTION: Thread-8
01-15 06:44:58.411: E/AndroidRuntime(1147): java.lang.NullPointerException
01-15 06:44:58.411: E/AndroidRuntime(1147): at com.yolanda.ta.ThreadUser.fetchLocal(ThreadUser.java:192)
01-15 06:44:58.411: E/AndroidRuntime(1147): at com.yolanda.ta.ThreadUser.run(ThreadUser.java:59)
01-15 06:44:58.492: W/ActivityManager(60): Force finishing activity com.yolanda.ta/.DBSynchronizer
and this is fetchLocal() to get data from database which I call it to get data from the local database
public String[] fetchLocal (int column)
{
Cursor user = mDbHelper.getAllRow3();
String Result[] = new String[user.getCount()];
user.moveToFirst();
int i = 0;
while (user.isAfterLast() == false) {
Result[i++] = user.getString(column);
user.moveToNext();
}
user.close();
return Result;
}
and this is the method of getAllRow3()
public Cursor getAllRow3()
{
Cursor c = db.query(NAMA_TABEL, new String[]{ROW_ID, ROW_NAMAL, ROW_NAMA, ROW_PW, ROW_ALAMAT, ROW_TELEPON, ROW_LEVEL, ROW_STATUS,ROW_TIME}, null, null, null, null, null, null);
return c;
}
and this is my table structure
public class DB_User {
private static final String ROW_ID = "IDUser";
private static final String ROW_NAMAL = "NamaLogin";
private static final String ROW_NAMA ="NamaUser";
private static final String ROW_PW ="PasswordUser";
private static final String ROW_ALAMAT ="AlamatUser";
private static final String ROW_TELEPON ="TeleponUser";
private static final String ROW_LEVEL ="LevelUser";
private static final String ROW_STATUS ="StatusUser";
private static final String ROW_TIME ="Waktu";
private static final String NAMA_DB = "TA";
private static final String NAMA_TABEL = "User";
private static final int DB_VERSION = 1;
private static int batas = 5;
private static final String CREATE_TABLE = "create table if not exists "+ NAMA_TABEL +" ("+ ROW_ID +" INTEGER PRIMARY KEY AUTOINCREMENT," +
ROW_NAMAL +" VARCHAR not null, "+ ROW_NAMA +" VARCHAR not null, " + ROW_PW + " VARCHAR not null, " + ROW_ALAMAT + " VARCHAR not null, "
+ ROW_TELEPON + " VARCHAR, "+ ROW_LEVEL+ " VARCHAR not null, " + ROW_STATUS + " INTEGER not null, "+ROW_TIME+" LONG not null)";
I don't have any idea since the other activity can get exactly the same data using the same query while my thread can't. Any suggestion is welcome.
EDIT:
line 192: Cursor user = mDbHelper.getAllRow3();
line 59: String[] LocalRowID = fetchLocal(0);
Here is my ThreadUser codes:
public class ThreadUser extends Thread implements Runnable {
private boolean RunSync = false;
private DB_User mDbHelper;
private long sleeptime;
public void setDatabase(DB_User mDbHelper)
{
this.mDbHelper = mDbHelper;
}
public void setRun(boolean set)
{
RunSync = set;
}
public void setDelay(long delay)
{
sleeptime = delay;
}
#Override
public void run()
{
while(RunSync)
{
String[] RemoteID = fetch("http://10.0.2.2/project/User.php?ct=Sel_IDUser");
String[] RemoteNamaL = fetch("http://10.0.2.2/project/User.php?ct=Sel_NamaLogin");
String[] RemoteNama = fetch("http://10.0.2.2/project/User.php?ct=Sel_NamaUser");
String[] RemotePassword = fetch("http://10.0.2.2/project/User.php?ct=Sel_PasswordUser");
String[] RemoteAlamat = fetch("http://10.0.2.2/project/User.php?ct=Sel_AlamatUser");
String[] RemoteTelepon = fetch("http://10.0.2.2/project/User.php?ct=Sel_TeleponUser");
String[] RemoteLevel = fetch("http://10.0.2.2/project/User.php?ct=Sel_LevelUser");
String[] RemoteStatus = fetch("http://10.0.2.2/project/User.php?ct=Sel_StatusUser");
String[] RemoteTime = fetch("http://10.0.2.2/project/User.php?ct=Sel_Waktu");
//ROW_ID, ROW_NAMAL, ROW_NAMA, ROW_PW, ROW_ALAMAT, ROW_TELEPON, ROW_LEVEL, ROW_STATUS,ROW_TIME
String[] LocalRowID = fetchLocal(0);
String[] LocalNamaL = fetchLocal(1);
String[] LocalNama = fetchLocal(2);
String[] LocalPassword = fetchLocal(3);
String[] LocalAlamat = fetchLocal(4);
String[] LocalTelepon = fetchLocal(5);
String[] LocalLevel = fetchLocal(6);
String[] LocalStatus = fetchLocal(7);
String[] LocalTime = fetchLocal(8);
Calendar cal = Calendar.getInstance();;
for(int i = 1; i < RemoteID.length; i++)
{ Log.e("index remote1", Integer.toString(i));
for(int j = 0; j < LocalRowID.length; j++)
{
Log.e("indexlocal1", Integer.toString(j));
if(RemoteID[i].equalsIgnoreCase(LocalRowID[j]))
{
if(Long.parseLong(RemoteTime[i]) > Long.parseLong(LocalTime[j]))
{
// //id, namal, nama, alamat, password, telepon, level, status, time
mDbHelper.updateBaris2(Integer.parseInt(LocalRowID[j]), RemoteNamaL[i],
RemoteNama[i], RemoteAlamat[i],RemotePassword[i],
RemoteTelepon[i], RemoteLevel[i], Integer.parseInt(RemoteStatus[i]), cal.getTimeInMillis());
break;
}
else if (Long.parseLong(RemoteTime[i]) < Long.parseLong(LocalTime[j]))
{
call("http://10.0.2.2/project/User.php?ct=EDT&namal="+LongData(LocalNamaL[j].toString())+
"&nama="+LongData(LocalNama[j].toString())+"&pw="+LongData(LocalPassword[j].toString())+"&alamat="+LongData(LocalAlamat[j].toString())+
"&telepon="+LongData(LocalTelepon[j].toString())+"&level="+LongData(LocalLevel[j].toString())+"&status="+LocalStatus[j]+"&time="
+cal.getTimeInMillis()+"&id="+LocalRowID[j].toString());
break;
}
}
}
if (LocalRowID.length + 1 > RemoteID.length)
{//namal, nama, alamat, password, telepon, level, status, time
try{
call("http://10.0.2.2/project/User.php?ct=INS&namal="+LongData(LocalNamaL[LocalRowID.length-1].toString())+
"&nama="+LongData(LocalNama[LocalRowID.length-1].toString())+"&pw="+LongData(LocalPassword[LocalRowID.length-1].toString())+"&alamat="+LongData(LocalAlamat[LocalRowID.length-1].toString())+
"&telepon="+LongData(LocalTelepon[LocalRowID.length-1].toString())+"&level="+LongData(LocalLevel[LocalRowID.length-1].toString())+"&status="+LocalStatus[LocalRowID.length-1]+"&time="
+cal.getTimeInMillis());
Log.e("nambah server","voila");
break;
}
catch (Exception e){Log.e("walah",e.toString());}
}
else
if (LocalRowID.length == RemoteID.length)
{
break;
}
}
for(int i = 0; i < LocalRowID.length-1; i++)
{ Log.e("index local2", Integer.toString(i));
if(RemoteID.length <= 1)
{
try{
call("http://10.0.2.2/project/User.php?ct=INS&namal="+LongData(LocalNamaL[i].toString())+
"&nama="+LongData(LocalNama[i].toString())+"&pw="+LongData(LocalPassword[i].toString())+"&alamat="+LongData(LocalAlamat[i].toString())+
"&telepon="+LongData(LocalTelepon[i].toString())+"&level="+LongData(LocalLevel[i].toString())+"&status="+LocalStatus[i]+"&time="
+cal.getTimeInMillis()+"&id="+LocalRowID[i].toString());
}
catch(Exception e){
Log.e("wooooy", e.toString());
}
}
for(int j = 1; j < RemoteID.length; j++)
{
Log.e("indexremote2", Integer.toString(j));
if(LocalRowID[i].equalsIgnoreCase(RemoteID[j]))
{
break;
}
if (LocalRowID.length == RemoteID.length)
{
break;
}
}
if (RemoteID.length-1 > LocalRowID.length)
{
i-=1;
try{
mDbHelper.addRow2(RemoteNamaL[RemoteID.length-1], RemoteNama[RemoteID.length-1], RemoteAlamat[RemoteID.length-1], RemotePassword[RemoteID.length-1],
RemoteTelepon[RemoteID.length-1], RemoteLevel[RemoteID.length-1], Integer.parseInt(RemoteStatus[RemoteID.length-1]), cal.getTimeInMillis());
break;
}
catch(Exception e){
Log.e("wuuuy", e.toString());
}
}
if (LocalRowID.length == RemoteID.length)
{
break;
}
}
try {
sleep(sleeptime);
} catch (InterruptedException e) {
break;
}
}
}
public String LongData (String Data)
{
String LongData ="";
for (int i = 0; i < Data.length(); i++)
{
if (Data.charAt(i)==' ')
{
LongData += '~';
}
else
LongData += Data.charAt(i);
}
return LongData;
}
public String[] fetchLocal (int column)
{
Cursor user = mDbHelper.getAllRow3();
String Result[] = new String[user.getCount()];
user.moveToFirst();
int i = 0;
while (user.isAfterLast() == false) {
Result[i++] = user.getString(column);
user.moveToNext();
}
user.close();
return Result;
}
public String[] fetch(String url)
{
HttpClient httpclient = new DefaultHttpClient();
HttpRequestBase httpRequest = null;
HttpResponse httpResponse = null;
InputStream inputStream = null;
String response = "";
StringBuffer buffer = new StringBuffer();
httpRequest = new HttpGet(url);
try
{
httpResponse = httpclient.execute(httpRequest);
}
catch (ClientProtocolException el)
{
el.printStackTrace();
}
catch (IOException el)
{
el.printStackTrace();
}
try
{
inputStream = httpResponse.getEntity().getContent();
}
catch (IllegalStateException el)
{
el.printStackTrace();
}
catch (IOException el)
{
el.printStackTrace();
}
byte[] data = new byte[512];
int len = 0;
try
{
while(-1 != (len = inputStream.read(data)))
{
buffer.append(new String(data,0,len));
}
}
catch (IOException el)
{
el.printStackTrace();
}
try
{
inputStream.close();
}
catch (IOException el)
{
el.printStackTrace();
}
response = buffer.toString();
StringParser parser = new StringParser();
ArrayList<Object> output = parser.Parse(response);
Object[] Output = output.toArray();
String[] content = new String[Output.length];
for (int i = 0; i < content.length; i++)
{
content[i] = Output[i].toString();
}
return content;
}
public String call(String url)
{
int BUFFER_SIZE = 2000;
InputStream in = null;
try
{
in = OpenHttpConnection(url);
}
catch (IOException el) {
el.printStackTrace();
return "Error: " + el.getMessage();
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try
{
while((charRead = isr.read(inputBuffer)) > 0)
{
String readString = String.copyValueOf(inputBuffer, 0, charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
}
catch (IOException e)
{
e.printStackTrace();
return "Error 02";
}
return str;
}
private InputStream OpenHttpConnection(String urlString) throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if(!(conn instanceof HttpURLConnection)) throw new IOException("Not an Http Connection");
try
{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if(response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception e)
{
throw new IOException("Error Connecting");
}
return in;
}
}`
First of all, your code don't have code line number, so we don't know which line is "ThreadUser.java:192" and "ThreadUser.java:59".
Actually this problem may be a synchronized problem, please provide more code detail about TheadUser.java code. If so please add synchronized to method or synchronized block to solve this issue.

Categories

Resources