sendUserActionEvent () mViwe == null error when using DB - android

i'm S4 user and my android ver. is 18(4.3.3).
um....while i make an app, i got some problem ( sendUserActionEvent () mViwe == null ), so i want someone's help. PLZ help me:)
here's my code where error has occurred
...
try{
body = m_et_inc_bdy.toString();
mny = Integer.parseInt(m_et_inc_mny.toString());
ord = yr*10000+mth*100+day;
m_dao.Append(body, mny, yr, mth, day, ord);
Toast.makeText(this, "REG success.", Toast.LENGTH_SHORT).show();
finish();
}catch(Exception ig)
{
Toast.makeText(this, "pre_DB_Error", Toast.LENGTH_LONG).show();
ig.printStackTrace();
finish();
}
...
and, m_dao.Append method is this code.
public void Append(String body, int mny, int yr, int mth, int day, int ord ) throws Exception{
str_query="'"+body+"',"+mny+","+yr+","+mth+","+day+","+ord;
_db_.execSQL("insert into HAC (body, money, dateyear, datemonth, dateday, ord) values("+str_query+") ");
}
i think i have no mistake in my code, but it doesn't work..(with logcat's error msg "sendUserActionEvent () mViwe == null")
can someone help me?? please:)
/* and, this is whole code*/
package com.example.accountbook;
import java.util.*;
import android.app.*;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.*;
import android.view.*;
import android.widget.*;
import com.example.accountbook.db.*;
public class InpIncActivity extends Activity implements View.OnClickListener{
private RankDAO m_dao = null;
private Button m_btn_date = null;
private Button m_btn_input = null;
private Button m_btn_cancel = null;
private EditText m_et_inc_bdy = null;
private EditText m_et_inc_mny = null;
private DatePickerDialog dlg = null;
private OnDateSetListener listener = null;
private int yr = 0;
private int mth = 0;
private int day = 0;
private int mny = 0;
private int ord = 0;
String body;
String date = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_in_inc);
setBindingButtons();
setBindingText();
setBingingDialog();
setBindingRank();
}
private void setBindingButtons()
{
m_btn_date=(Button)findViewById(R.id.btn_ia_date);
m_btn_input=(Button)findViewById(R.id.btn_ia_input);
m_btn_cancel=(Button)findViewById(R.id.btn_ia_cancel);
m_btn_date.setOnClickListener(this);
m_btn_input.setOnClickListener(this);
m_btn_cancel.setOnClickListener(this);
}
private void setBindingText()
{
m_et_inc_bdy=(EditText)findViewById(R.id.et_ia_bd);
m_et_inc_mny=(EditText)findViewById(R.id.et_ia_mny);
}
public void onClick(View v)
{
if(v==m_btn_date)
{
dlg.show();
}
else if(v==m_btn_input)
{
try{
body=m_et_inc_bdy.toString();
mny=Integer.parseInt(m_et_inc_mny.toString());
ord=yr*10000+mth*100+day;
m_dao.Append(body, mny, yr, mth, day, ord);
Toast.makeText(this, "REG success", Toast.LENGTH_SHORT).show();
finish();
}catch(Exception ig)
{
Toast.makeText(this, "pre_DB_Error", Toast.LENGTH_LONG).show();
ig.printStackTrace();
finish();
}
}
else if(v==m_btn_cancel)
{
finish();
}
}
public void setBingingDialog()
{
this.listener = new OnDateSetListener()
{
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
yr=year;
mth=monthOfYear+1;
day=dayOfMonth;
if(mth<10)
date=String.valueOf(yr)+".0"+String.valueOf(mth)+"."+String.valueOf(day);
else
date=String.valueOf(yr)+"."+String.valueOf(mth)+"."+String.valueOf(day);
m_btn_date.setText(date);
}
};
this.dlg=new DatePickerDialog(this, listener,Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DATE));
}
public void setBindingRank()
{
try{
m_dao=RankDAO.GetInstance(this);
}catch(Exception e){
Toast.makeText(this, "DB ERROR", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
package com.example.accountbook.db;
import java.util.*;
import com.example.accountbook.*;
import android.app.*;
import android.database.*;
import android.database.sqlite.*;
public class RankDAO {
private static RankDAO _instance_ = null;
private static Activity _activity_ = null;
private SQLiteDatabase _db_ = null;
private int year = 0;
private int month = 0;
private int day = 0;
private int money = 0;
String body = null;
String val = null;
String str_query = null;
private RankDAO() throws Exception{
super();
OpenDatabase();
}
public static synchronized RankDAO GetInstance(Activity act) throws Exception{
if(_instance_ == null) {
_activity_ = act;
_instance_ = new RankDAO();
}
return _instance_;
}
private void OpenDatabase() throws Exception {
try{
if(_db_ == null){
_db_ = _activity_.openOrCreateDatabase("db", Activity.MODE_PRIVATE, null);
//_db_.execSQL("drop table HAC");
_db_.execSQL("Create Table IF NOT EXISTS HAC (body varchar(127), money int(8), dateyear int(4), datemonth int(2), dateday int(2), ord int(8) )");
// _db_AC.execSQL("Create Index IF NOT EXISTS IDX_HAC ON HAC (dateyear asc, datemonth asc, dateday asc)");
}
}catch(Exception ig){
ig.printStackTrace();
throw ig;
}
}
public void Append(String body, int mny, int yr, int mth, int day, int ord ) throws Exception{
str_query="'"+body+"',"+mny+","+yr+","+mth+","+day+","+ord;
_db_.execSQL("insert into HAC (body, money, dateyear, datemonth, dateday, ord) values("+str_query+") ");
}
public ArrayList<HashMap<String,String >> GetRankData(){
ArrayList<HashMap<String,String>> _Items = new ArrayList<HashMap<String,String>>();
Cursor _cursor = _db_.rawQuery("Select * From HAC Order By ord desc ", null);
if(_cursor.moveToFirst()){
do{
body = _cursor.getString(0);
money = Integer.parseInt(_cursor.getString(1));
year = Integer.parseInt(_cursor.getString(2));
month = Integer.parseInt(_cursor.getString(3));
day = Integer.parseInt(_cursor.getString(4));
val =String.valueOf(year)+"."+String.valueOf(month)+"."+String.valueOf(day)+"\t"+String.valueOf(money);
HashMap<String,String> _Item = new HashMap<String,String>();
_Item.put("value",val); // No. 이름
_Item.put("body", body); // 시간
_Items.add(_Item);
MainActivity.mymoney(money);
if(year==Calendar.getInstance().get(Calendar.YEAR) && month==Calendar.getInstance().get(Calendar.MONTH) && day==Calendar.getInstance().get(Calendar.DATE))
MainActivity.todinc(money);
}while(_cursor.moveToNext());
_cursor.close();
}
return _Items;
}
}

Related

When using setOnGroupClickListener method report an error “cannot find symbol”

When using setOnGroupClickListener method report an error “cannot find symbol”,
I try to use setOnGroupClickListener to register sublist click event listener to list control,But an error is reported during compilation
error report:
vendor/proprietary/modem/ModemTestBox/src/com/xiaomi/mtb/activity/MtbNvAutoCheckList1Activity.java:142: error: cannot find symbol
elvBook.setOnGroupClickListener(new ExpandableListView.setOnGroupClickListener(){
vendor/proprietary/modem/ModemTestBox/src/com/xiaomi/mtb/activity/MtbNvAutoCheckList1Activity.java:143: error: method does not override or implement a method from a supertype
#Override
package com.mtb.activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import com.xiaomi.mtb.*;
import com.xiaomi.mtb.activity.*;
import com.xiaomi.mtb.R;
import android.util.Log;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MtbNvAutoCheckList1Activity extends MtbBaseActivity {
private ArrayList<NvAutoCheckDataFather> groups = new ArrayList<>();
private ArrayList<ArrayList<NvAutoCheckDataSon>>children = new ArrayList<>();
private ArrayList<NvAutoCheckDataSon>data=new ArrayList<>();
private HashMap<Integer,Integer>hashMap=new HashMap<>();
private static int mNvEfsDataPrintMaxNum = 20;
private static final String LOG_TAG = "MtbNvAutoCheckMainActivity";
private static final int DATA_TYPE_DECIMALISM = 0;
private static int mHexOrDec = DATA_TYPE_DECIMALISM;
private static final int DATA_TYPE_HEX = 1;
private static final int SIGNED_DATA = 0;
private static final int UNSIGNED_DATA = 1;
private static boolean mTmpLogPrintFlag = false;
private ExpandableListView elvBook;
private NvAutoCheckBookAdapter adapter;
private static HashMap<Integer,byte[]>mNvData=new HashMap<Integer,byte[]>(){
{
put(550,new byte[]{8,(byte)138, 70, 115, 6, 98, 16, 5, 112});
put(74,new byte[]{6});
put(453,new byte[]{1});
}
};
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMtbHookAgent = MtbHookAgent.getHook();
int num=0;
Iterator<Map.Entry<Integer,byte[]>> iterator1=mNvData.entrySet().iterator();
while(iterator1.hasNext()){
Map.Entry<Integer,byte[]>entry=iterator1.next();
int key=entry.getKey();
byte[] value=entry.getValue();
ByteBuffer byteBuf=mMtbHookAgent.onHookNvOptSync(0, key, mMtbHookAgent.EVENT_OEMHOOK_XIAOMI_NV_READ);
log("onNvEfsReadHookHdl, mNvId = "+key);
int ret = byteBuf.getInt();
int len = byteBuf.getInt();
log("onNvEfsReadHookHdl" + ", len = " + len);
byte[] bytes = null;
if(len<=0){
log("efs config empty");
}else{
bytes = new byte[len];
byteBuf.get(bytes);
}
String mNvFlagResult="false";
for(int i=0; i < value.length;i++){
if(entry.getValue()[i] != bytes[i]){
log("mNVDATA_"+key+"[" + i + "] not the same");
break;
}
log("mNVDATA_"+key+"[" + i + "] identical");
if(i == (value.length - 1)){
mNvFlagResult = "success";
}
}
groups.add(new NvAutoCheckDataFather(key,mNvFlagResult));
if(mNvFlagResult=="false"){
hashMap.put(num, hashMap.size());
NvAutoCheckDataSon mNvAutoCheckDataSon=new NvAutoCheckDataSon("正确的值是: "+onGetStringByByteGroup(value,value.length),"读出的值为: "+onGetStringByByteGroup(bytes,value.length));
children.add(new ArrayList<NvAutoCheckDataSon>(){
{
add(mNvAutoCheckDataSon);
}
});
}
num++;
}
// 利用布局资源文件设置用户界面
setContentView(R.layout.nv_auto_check_list1_config);
// 通过资源标识获得控件实例
elvBook = findViewById(R.id.elvBook);
// 创建适配器
adapter = new NvAutoCheckBookAdapter(this, groups, children, hashMap);
// 给列表控件设置适配器
elvBook.setAdapter(adapter);
// 给列表控件注册子列表单击事件监听器
elvBook.setOnGroupClickListener(new ExpandableListView.setOnGroupClickListener(){
#Override
public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition,long l){
if(!hashMap.containsKey(groupPosition)){
return true;
}else{
return false;
}
}
});
}
private static void log(String msg) {
Log.d(LOG_TAG, "MTB_ " + msg);
}
private String onGetStringByDateType(byte val, int uFlag, boolean bPrint) {
return onGetStringByDateType(val, uFlag, bPrint, mHexOrDec, true);
}
private String onGetStringByDateType(byte val, int uFlag, boolean bPrint, int hexOrDec, boolean fillHexZero) {
if (bPrint) {
tmpLog("onGetStringByDateType, byte, val = " + val + ", uFlag = " + uFlag + ", bPrint = " + bPrint + ", hexOrDec = " + hexOrDec + ", fillHexZero = " + fillHexZero);
}
String strVal = null;
BigDecimal bigVal;
byte lowVal = 0;
if (DATA_TYPE_HEX == hexOrDec) {
strVal = Integer.toHexString(val & 0xff);
if (1 == strVal.length() && fillHexZero) {
strVal = "0" + strVal;
}
if (bPrint) {
tmpLog("HEX, strVal = " + strVal);
}
} else {
strVal = "" + val;
if (UNSIGNED_DATA == uFlag && val < 0) {
lowVal = (byte)(val & 0x7f);
bigVal = BigDecimal.valueOf(lowVal).add(BigDecimal.valueOf(Byte.MAX_VALUE)).add(BigDecimal.valueOf(1));
strVal = bigVal.toString();
if (bPrint) {
tmpLog("val < 0, new strVal = " + strVal);
}
}
}
if (null != strVal) {
strVal = strVal.toUpperCase();
}
return strVal;
}
private String onGetStringByByteGroup(byte[] bytes, int len){
String ret="";
for(int i=0;i<len;i++){
String str1=onGetStringByDateType(bytes[i], UNSIGNED_DATA, false);
ret+=str1;
}
return ret;
}
private static void tmpLog(String msg) {
if (mTmpLogPrintFlag) {
log(msg);
}
}
}

ProgressDialog.show() is not showing the progress dialog

I am trying to display a progress dialog inside a fragment.But progressbar.show() do not have any effect.However,I noticed a strange behaviour,if i call showPopUp() method twice,it does show the progress dialog,but unable to dismiss().
package com.snapbizz.snapdashboard.Tabs.v1;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.snapbizz.snapdashboard.Core.v1.SalesData;
import com.snapbizz.snapdashboard.R;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class DashBoardSalesTab extends Fragment {
LinearLayout salesListContainer, salesBarConatainer;
LayoutInflater layoutInflater;
SalesData salesData;
ProgressDialog progressDialog;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sales_page_layout, container, false);
return rootView;
}
public void showPopUp() {
progressDialog = new ProgressDialog(getContext(), ProgressDialog.THEME_HOLO_LIGHT);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("loading the page...");
progressDialog.setProgressNumberFormat(null);
progressDialog.setProgressPercentFormat(null);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
public void synchronizeScrollers() {
getActivity().findViewById(R.id.page_scroller).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
getActivity().findViewById(R.id.table_scroller).getParent()
.requestDisallowInterceptTouchEvent(true);
return false;
}
});
getActivity().findViewById(R.id.table_scroller).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
}
public void renderSalesGraph(List<String[]> values, Float totalSumY) throws Exception {
salesBarConatainer.removeAllViews();
for (String[] value : values) {
View barView = layoutInflater.inflate(R.layout.bar_char_item_layout, salesBarConatainer, false);
float sumOfSalesForTheDay = Float.parseFloat((value[0] == null) ? "0" : value[0]);
float weightofBar = sumOfSalesForTheDay / totalSumY;
barView.findViewById(R.id.bar_y).setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, weightofBar));
((TextView) barView.findViewById(R.id.value_y)).setText(
(sumOfSalesForTheDay == 0.0f ? "" :
getActivity().getResources().getString(R.string.rupee_symbol) + sumOfSalesForTheDay + "")
);
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MMM-yyyy");
Date renderingDate = inputFormat.parse(value[2]);
String[] date = outputFormat.format(renderingDate).split("-");
((TextView) barView.findViewById(R.id.value_x_date)).setText(date[0] + " " + date[1]);
((TextView) barView.findViewById(R.id.value_x_year)).setText(date[2]);
salesBarConatainer.addView(barView);
}
}
public void renderSalesGraphForMonths(List<String[]> values, Float totalSumY) throws Exception {
LinearLayout salesBarConatainer = (LinearLayout) getActivity().findViewById(R.id.bars_container);
salesBarConatainer.removeAllViews();
for (String[] value : values) {
View barView = layoutInflater.inflate(R.layout.bar_char_item_layout, salesBarConatainer, false);
float sumOfSalesForTheDay = Float.parseFloat((value[0] == null) ? "0" : value[0]);
float weightofBar = sumOfSalesForTheDay / totalSumY;
barView.findViewById(R.id.bar_y).setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, weightofBar));
((TextView) barView.findViewById(R.id.value_y)).setText(
(sumOfSalesForTheDay == 0.0f ? "" :
getActivity().getResources().getString(R.string.rupee_symbol) + sumOfSalesForTheDay + "")
);
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy/MM");
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM-yyyy");
Date renderingDate = inputFormat.parse(value[2]);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, renderingDate.getMonth());
cal.set(Calendar.DAY_OF_MONTH, 1);
barView.setOnClickListener(new MonthBarClickListener(cal));
String[] date = outputFormat.format(renderingDate).split("-");
((TextView) barView.findViewById(R.id.value_x_date)).setText(date[0]);
((TextView) barView.findViewById(R.id.value_x_year)).setText(date[1]);
salesBarConatainer.addView(barView);
}
}
public String[] addTOSalesTable(String date, boolean header) throws Exception {
List<String[]> values = salesData.getSalesTableData(date);
String[] value = values.get(0);
String[] newValue = {value[0], value[1], date};
String totalSales = (value[0] == null) ? "0" : value[0];
String totalCredit = (value[1] == null) ? "0" : value[1];
String totalCash = (Float.parseFloat(totalSales) - Float.parseFloat(totalCredit)) + "";
String rupeeSymbol = getActivity().getResources().getString(R.string.rupee_symbol);
if (!header) {
View salesRow = layoutInflater.inflate(R.layout.sales_page_table_row_layout, salesListContainer, false);
((TextView) (salesRow.findViewById(R.id.sale_date))).
setText(date);
((TextView) (salesRow.findViewById(R.id.sales_total_sale))).
setText(rupeeSymbol + " " + totalSales);
((TextView) (salesRow.findViewById(R.id.sales_total_cash))).
setText(rupeeSymbol + " " + totalCash);
((TextView) (salesRow.findViewById(R.id.sales_total_credit))).
setText(rupeeSymbol + " " + totalCredit);
((TextView) (salesRow.findViewById(R.id.sales_ttoal_coupon))).
setText(rupeeSymbol + " " + "0");
if (salesListContainer.getChildCount() % 2 != 0) {
salesRow.setBackgroundColor(getResources().getColor(R.color.table_row_alternate_color));
}
salesListContainer.addView(salesRow);
} else {
((TextView) (getActivity().findViewById(R.id.sales_header_total_sales))).
setText(rupeeSymbol + " " + totalSales);
((TextView) (getActivity().findViewById(R.id.sales_header_total_cash))).
setText(rupeeSymbol + " " + totalCash);
((TextView) (getActivity().findViewById(R.id.sales_header_total_credit))).
setText(rupeeSymbol + " " + totalCredit);
((TextView) (getActivity().findViewById(R.id.sales_header_total_coupon))).
setText(rupeeSymbol + " " + "0");
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date presentDate = new Date();
((TextView) (getActivity().findViewById(R.id.sales_header_day))).
setText(date.contentEquals(dateFormat.format(presentDate)) ? "Today" : date);
}
return newValue;
}
public void getMonths() throws Exception {
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM");
List<String[]> values = new ArrayList<>();
float totalSumY = 0.0f;
for (int i = 0; i < 12; i++) {
cal.add(Calendar.MONTH, (i == 0) ? 0 : -1);
String date = dateFormat.format(cal.getTime());
String[] value = salesData.getSalesDataForMonth(date);
String[] newValue = {value[0] == null ? "0" : value[0], value[1] == null ? "0" : value[1], date};
totalSumY += Float.parseFloat(value[0] == null ? "0" : value[0]);
values.add(newValue);
}
renderSalesGraphForMonths(values, totalSumY);
}
public void initChart() {
FrameLayout dayButton = (FrameLayout) getActivity().findViewById(R.id.day_button);
FrameLayout monthButton = (FrameLayout) getActivity().findViewById(R.id.month_button);
dayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
((TextView) getActivity().findViewById(R.id.button_day_text)).setTextColor(
getResources().getColor(R.color.dark_darkblue)
);
((TextView) getActivity().findViewById(R.id.button_day_text)).
setBackground(getResources().getDrawable(R.drawable.button_border_active));
((TextView) getActivity().findViewById(R.id.button_month_text)).setTextColor(
getResources().getColor(R.color.default_text_color)
);
((TextView) getActivity().findViewById(R.id.button_month_text)).
setBackground(getResources().getDrawable(R.drawable.button_border));
generateTablesRows(Calendar.getInstance(), 60, -1);
} catch (Exception e) {
e.printStackTrace();
}
}
});
monthButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
((TextView) getActivity().findViewById(R.id.button_month_text)).setTextColor(
getResources().getColor(R.color.dark_darkblue)
);
((TextView) getActivity().findViewById(R.id.button_month_text)).
setBackground(getResources().getDrawable(R.drawable.button_border_active));
((TextView) getActivity().findViewById(R.id.button_day_text)).setTextColor(
getResources().getColor(R.color.default_text_color)
);
((TextView) getActivity().findViewById(R.id.button_day_text)).
setBackground(getResources().getDrawable(R.drawable.button_border));
getMonths();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void generateTablesRows(Calendar cal, int limit, int increment) throws Exception {
salesListContainer.removeAllViews();
float totalSumY = 0.0f;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
List<String[]> barGraphValues = new ArrayList<>();
for (int i = 0; i < limit; i++) {
cal.add(Calendar.DATE, (i == 0) ? 0 : increment);
String date = dateFormat.format(cal.getTime());
String[] value = addTOSalesTable(date, (i == 0) ? true : false);
totalSumY += Float.parseFloat((value[0] == null) ? "1" : value[0]);
barGraphValues.add(value);
}
renderSalesGraph(barGraphValues, totalSumY);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
showPopUp();
layoutInflater = LayoutInflater.from(getContext());
salesListContainer = (LinearLayout) (getActivity().findViewById(R.id.sales_list_container));
salesListContainer.removeAllViews();
salesBarConatainer = (LinearLayout) getActivity().findViewById(R.id.bars_container);
salesBarConatainer.removeAllViews();
new SalesTabLoader().execute();
}
public class MonthBarClickListener implements View.OnClickListener {
Calendar cal;
public MonthBarClickListener(Calendar cal) {
this.cal = cal;
}
#Override
public void onClick(View v) {
try {
//new SalesAsyncTask(cal).execute(cal.getActualMaximum(Calendar.DAY_OF_MONTH),1);
generateTablesRows(cal, cal.getActualMaximum(Calendar.DAY_OF_MONTH), 1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class SalesTabLoader extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
salesData = new SalesData(getContext());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
initChart();
generateTablesRows(Calendar.getInstance(), 60, -1);
} catch (Exception e) {
e.printStackTrace();
} finally {
synchronizeScrollers();
progressDialog.dismiss();
}
}
}
}
Try like this :
progressDialog = new ProgressDialog(getActivity());
And if you wish to customize your dialog and put self created Layout in it.
/**
* Created by vivek on 18/10/16.
*/
public class CustomDialog {
private static Dialog dialog;
private static Context context;
public CustomDialog(Context context) {
this.context = context;
}
/**
* Comman progress dialog ... initiates with this
*
* #param message
* #param title
*/
public static void showProgressDialog(Context context, String title, String message) {
if (dialog == null)
{
dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_loader);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
}
public static boolean isProgressDialogRunning() {
if (dialog != null && dialog.isShowing()) {
return true;
} else return false;
}
/**
* Dismiss comman progress dialog
*/
public static void dismissProgressDialog() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
dialog = null;
}
}
} // End of main class over here ...
Replace this:-
progressDialog = new ProgressDialog(getContext(), ProgressDialog.THEME_HOLO_LIGHT);
with
progressDialog = new ProgressDialog(getActivity());
May be. you are showing two progressdialog and both of that progressbar on screen.. but when you dismiss your progressbar at that time the previous one is override by other one before you dismiss first one .. so the firstone is always in screen. that's the issue.
I tried everything.But none of the answers solved the issue.However,i solved it by overriding onResume() method in the fragment.
Thanks All.

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

get return Value null in method in android

I write one function for get data from database.
I have set a breakpoint and make sure the function is already get data for return
but when I use the function I Can't get data back in My main function
is my data structure error? or other thing error?
thanks for your help.
import java.util.ArrayList;
public class ScheduleData {
public String strID;
public String strName;
public String strDesc;
public Integer iScheduleDay;
public String strStartDate;
public ArrayList<ScheduleContent> alPOI;
public ScheduleData() {
strID = new String();
strName = new String();
strDesc = new String();
strStartDate = new String();
iScheduleDay = 0;
alPOI = new ArrayList<ScheduleContent>();
}
}
//
public class ScheduleContent {
public String strPOIID;
public int iSequence ;
public int iDay ;
public String strTime;
public int iStayTime ;
public ScheduleContent() {
iSequence = 1;
iDay = 1;
iStayTime = 0;
}
}
//
public boolean bInitData() {
ArrayList<ScheduleData> alEx = alGetAllSchedule();
}
private ArrayList<ScheduleData> alGetAllSchedule() {
ArrayList<ScheduleData> alTmp = new ArrayList<ScheduleData>();
try {
mDATA.m_alAllSchedule.clear();
Cursor c = objSchedule.getAllCursor();
ScheduleDataInit();
if (c.getCount() > 0) {
if (c.moveToFirst()) {
while (c.isAfterLast() == false) {
ScheduleData sTmp = new ScheduleData();
sTmp.strID = c.getString(c.getColumnIndex("SID"));
sTmp.strName = c.getString(c.getColumnIndex("S_Name"));
sTmp.strDesc = c.getString(c.getColumnIndex("S_Desc"));
sTmp.strStartDate = c.getString(c
.getColumnIndex("S_StartDate"));
sTmp.iScheduleDay = Integer.valueOf(c.getInt(c
.getColumnIndex("S_Day")));
sTmp.alPOI=mDATA.m_hAllScheduleContent.get(sTmp.strID);
alTmp.add(sTmp);
c.moveToNext();
}
}
}
mDATA.m_alAllSchedule = alTmp;
c.close();
} catch (Exception errMsg) {
errMsg.printStackTrace();
}
return alTmp;
}

Android widget get touch position

is it possible to get the position of a touch when the user touches my widget on the homescreen? TIA
edit: my widget code:
public class MyWidgetProvider extends AppWidgetProvider {
public static String ACTION_WIDGET_MEMO = "comNgarsideMemoActionWidgetMemo";
public static String ACTION_WIDGET_PEN = "comNgarsideMemoActionWidgetPen";
public static String ACTION_WIDGET_ERASER = "comNgarsideMemoActionWidgetEraser";
public static String ACTION_WIDGET_UNDO = "comNgarsideMemoActionWidgetUndo";
public static String ACTION_WIDGET_REDO = "comNgarsideMemoActionWidgetRedo";
public static String ACTION_WIDGET_SAVE = "comNgarsideMemoActionWidgetSave";
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
Intent memoIntent = new Intent(context, ListActivity.class);
memoIntent.setAction(ACTION_WIDGET_MEMO);
Intent penIntent = new Intent(context, MyWidgetProvider.class);
penIntent.setAction(ACTION_WIDGET_PEN);
Intent eraserIntent = new Intent(context, MyWidgetProvider.class);
eraserIntent.setAction(ACTION_WIDGET_ERASER);
Intent undoIntent = new Intent(context, MyWidgetProvider.class);
undoIntent.setAction(ACTION_WIDGET_UNDO);
Intent redoIntent = new Intent(context, MyWidgetProvider.class);
redoIntent.setAction(ACTION_WIDGET_REDO);
Intent saveIntent = new Intent(context, MyWidgetProvider.class);
saveIntent.setAction(ACTION_WIDGET_SAVE);
PendingIntent memoPendingIntent = PendingIntent.getActivity(context, 0, memoIntent, 0);
PendingIntent penPendingIntent = PendingIntent.getBroadcast(context, 0, penIntent, 0);
PendingIntent eraserPendingIntent = PendingIntent.getBroadcast(context, 0, eraserIntent, 0);
PendingIntent undoPendingIntent = PendingIntent.getBroadcast(context, 0, undoIntent, 0);
PendingIntent redoPendingIntent = PendingIntent.getBroadcast(context, 0, redoIntent, 0);
PendingIntent savePendingIntent = PendingIntent.getBroadcast(context, 0, saveIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.iconBtn, memoPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.penBtn, penPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.eraserBtn, eraserPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.undoBtn, undoPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.redoBtn, redoPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.saveBtn, savePendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
this.onDeleted(context, new int[] { appWidgetId });
}
} else {
if (intent.getAction().equals(ACTION_WIDGET_PEN)) {
} else if (intent.getAction().equals(ACTION_WIDGET_ERASER)) {
} else if (intent.getAction().equals(ACTION_WIDGET_UNDO)) {
} else if (intent.getAction().equals(ACTION_WIDGET_REDO)) {
} else if (intent.getAction().equals(ACTION_WIDGET_SAVE)) {
}
super.onReceive(context, intent);
}
}
}
Maybe this will give you an idea...
PressureDynamics.java
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.util.Log;
/**
* Keyboard sensor
*/
public class PressureDynamics extends Thread implements FeatureExtractor{
public static final String AVG_TOUCH_PRESSURE = "Avg_Touch_Pressure";
public static final String AVG_TOUCH_AREA = "Avg_Touch_Area";
private static final int EVENT_BYTE_SIZE = 16;
private InputStream _fis = null;
private boolean _shouldRun;
private Map<String, TouchScreenSensor> _sensors;
public PressureDynamics(Context context, Collection<FeatureInfo> featureInfos,
Long timeStamp){
super("Pressure Dynamics Feature Extractor Thread");
_shouldRun = true;
_sensors = new HashMap<String, TouchScreenSensor>();
int featureCount = 0;
for (FeatureInfo featureInfo : featureInfos){
String name = featureInfo.name;
try{
if (name.equalsIgnoreCase(AVG_TOUCH_PRESSURE)){
TouchScreenSensor s = new AvgTouchPressureSensor(featureInfo);
_sensors.put(AVG_TOUCH_PRESSURE, s);
}else if (name.equalsIgnoreCase(AVG_TOUCH_AREA)){
TouchScreenSensor s = new AvgTouchAreaSensor(featureInfo);
_sensors.put(AVG_TOUCH_AREA, s);
}else{
Log.e(FE_TAG, "Unhandled feature by " + getClass().getCanonicalName()
+ ": " + name);
continue;
}
++featureCount;
}catch(RuntimeException e){
Log.e(FE_TAG, "Unable to initialize feature: " + name, e);
}
}
if (featureCount == 0){
throw new FeatureExtractorInitException("No features of "
+ getClass().getCanonicalName() + " could be initialized");
}
_fis = openTouchScreenInputStream();
start();
}
private static InputStream openTouchScreenInputStream(){
final String HTC_TOUCH_SCREEN_INPUT_FILEPATH = "/dev/input/event1";
LocalServerConn localServerConn;
try{
localServerConn = LocalServerConn.getInstance();
localServerConn.runLocalServer();
}catch(Exception e){
throw new FeatureExtractorInitException(
"Unable to collect Touch Screen features", e);
}
try{
FileDescriptor[] fdArr = localServerConn
.sendFileDescriptorReq(HTC_TOUCH_SCREEN_INPUT_FILEPATH);
if (fdArr == null || fdArr.length == 0){
throw new FeatureExtractorInitException("Can't open keyboard device");
}
return new FileInputStream(fdArr[0]);
}catch(IOException e){
throw new FeatureExtractorInitException("Can't open keyboard input stream: "
+ e.getMessage(), e);
}
}
public void close(){
_shouldRun = false;
}
public void collectData(List<MonitoredData> monitoredData, ParcelableDate endTime){
for (Sensor s : _sensors.values()){
s.collectData(monitoredData, endTime);
}
}
public void run(){
int n;
int pos = 0;
byte[] buffer = new byte[256];
for (;;){
try{
n = _fis.read(buffer, pos, EVENT_BYTE_SIZE);
/*
* check if we are shutting down - this may have the thread hanging around
* until the next touch event comes in
*/
if (_shouldRun == false){
break;
}
pos += n;
// Log.v(FE_TAG, "read touch screen event: " + n + " bytes\n");
if (pos >= EVENT_BYTE_SIZE){
long currentTimeMillis = System.currentTimeMillis();
TouchEvent touchScreenEvent = new TouchEvent(buffer,
currentTimeMillis);
updateSensors(touchScreenEvent, currentTimeMillis);
pos -= EVENT_BYTE_SIZE;
}
}catch(IOException e){
Log.e(FE_TAG, e.getMessage(), e);
}
}
}
private void updateSensors(TouchEvent touchScreenEvent, long currentTimeMillis){
try{
// currently filter out all non preassure event types
//
switch ((int)touchScreenEvent.getCode()){
case TouchEvent.X_POS_EVENT:
case TouchEvent.Y_POS_EVENT:
case TouchEvent.TOUCH_DEVICE_TYPE_EVENT:
break;
case TouchEvent.ABS_PRESSURE_EVENT:
_sensors.get(AVG_TOUCH_PRESSURE).updateSensor(touchScreenEvent,
currentTimeMillis);
break;
case TouchEvent.ABS_TOOL_WIDTH_EVENT:
_sensors.get(AVG_TOUCH_AREA).updateSensor(touchScreenEvent,
currentTimeMillis);
break;
default:
Log.e(FE_TAG, "unrecognized touch event code :"
+ touchScreenEvent.getCode());
break;
}
}catch(Exception e){
Log.e(FE_TAG, e.getMessage(), e);
}
}
public String toString(){
return getClass().getSimpleName();
}
private static abstract class TouchScreenSensor extends Sensor{
private TouchScreenSensor(String name, FeatureInfo info){
//super(name, info.getValueTimeout());
super(name);
}
public abstract void updateSensor(TouchEvent event, long currentTimeMillis);
}
private static class AvgTouchPressureSensor extends TouchScreenSensor{
public AvgTouchPressureSensor(FeatureInfo info){
super(AVG_TOUCH_PRESSURE, info);
}
public void updateSensor(TouchEvent event, long currentTimeMillis){
addToAvg(event.getValue(), currentTimeMillis);
}
}
private static class AvgTouchAreaSensor extends TouchScreenSensor{
public AvgTouchAreaSensor(FeatureInfo info){
super(AVG_TOUCH_AREA, info);
}
public void updateSensor(TouchEvent event, long currentTimeMillis){
addToAvg(event.getValue(), currentTimeMillis);
}
}
}
Sensor.java
import java.util.List;
public class Sensor{
private final String _name;
private Double _avg;
private int _count;
private long _lastValueUpdateTime;
/**
* Constructor
*
* #param name The name of the feature that is collected by this sensor
* #param valueTimeout The time period of no value changes it takes for the current
* value to reset to the initial value (in millis)
*/
public Sensor(String name){
_lastValueUpdateTime = 0;
_name = name;
_avg = null;
_count = 0;
}
public void collectData(List<MonitoredData> monitoredData, ParcelableDate endTime){
Double value = getValue(endTime.getTime());
if (value != null){
value = Utils.truncateDouble(value);
}
monitoredData.add(new MonitoredData(_name, value, endTime));
}
public Double getValue(long time){
if (time - _lastValueUpdateTime > MainActivity.getAgentLoopTime()){
_avg = null;
_count = 0;
}
return _avg;
}
public String getName(){
return _name;
}
public void addToAvg(double value, long time){
Double avg = getValue(time);
if (avg == null){
avg = value; // Initial value
}else{
value = (avg * _count + value) / (_count + 1);
}
++_count;
_avg = value;
_lastValueUpdateTime = time;
}
#Override
public String toString(){
return _name;
}
}
TouchEvent.java
import android.util.Log;
import dt.util.Utils;
public class TouchEvent{
public static final int ABS_PRESSURE_EVENT = 0x18;
public static final int ABS_TOOL_WIDTH_EVENT = 0x1c;
public static final int X_POS_EVENT = 0x0;
public static final int Y_POS_EVENT = 0x1;
/* type of touching device ie. finger, stylus etc. */
public static final int TOUCH_DEVICE_TYPE_EVENT = 0x14a;
// private final long _timeStamp;
// private final int _sec;
// private final int _usec;
// 3, 1, 0 - ?
// private final long _type;
// different event types have different codes
private final long _code;
private final int _value;
//
public TouchEvent(byte[] _buffer, long currentTimeMillis){
int pos;
byte b[] = new byte[4];
byte s[] = new byte[2];
// _timeStamp = currentTimeMillis;
pos = 0;
// _sec = Utils.LittleEndianBytesToInt(_buffer);
pos += 4;
System.arraycopy(_buffer, pos, b, 0, 4);
// _usec = Utils.LittleEndianBytesToInt(b);
pos += 4;
// _type = Utils.LittleEndianBytesToUShort(s);
pos += 2;
System.arraycopy(_buffer, pos, s, 0, 2);
_code = Utils.littleEndianBytesToUShort(s);
pos += 2;
System.arraycopy(_buffer, pos, b, 0, 4);
_value = Utils.littleEndianBytesToInt(b);
if (_code != X_POS_EVENT && _code != Y_POS_EVENT
&& _code != TOUCH_DEVICE_TYPE_EVENT && _code != ABS_PRESSURE_EVENT
&& _code != ABS_TOOL_WIDTH_EVENT){
Log.d(FE_TAG, "unrecognized touch event code :" + _code);
}
}
public long getCode(){
return _code;
}
public double getValue(){
return _value;
}
}
FeatureInfo.java
import java.util.HashMap;
public class FeatureInfo{
/** The name of the feature */
public final String name;
/** The parameters relevant to the feature */
public final HashMap<String, String> params;
/**
* Constructs a FeatureInfo object from the given parameters
*
* #param name The name of the feature
* #param params The parameters relevant to the feature
*/
public FeatureInfo(String name, HashMap<String, String> params){
this.name = name;
this.params = (params == null) ? new HashMap<String, String>() : params;
}
#Override
public String toString(){
return name;
}
public int getTimeWindow() throws IllegalArgumentException{
final String paramName = "Time_Window";
try{
int timeWindow = Integer.parseInt(params.get(paramName)) * 1000;
if (timeWindow <= 0){
throw new IllegalArgumentException("Must be a positive integer");
}
return timeWindow;
}catch(Exception e){// NullPointer or Parsing
throw new IllegalArgumentException("Corrupt parameter: " + paramName
+ " in feature " + name, e);
}
}
// public int getTimeWindow() throws IllegalArgumentException{
// final String paramName = "Time_Window";
// try{
// int timeWindow = Integer.parseInt(params.get(paramName)) * 1000;
// if (timeWindow <= 0){
// throw new IllegalArgumentException("Must be a positive integer");
// }
// return timeWindow;
// }catch(Exception e){// NullPointer or Parsing
// throw new IllegalArgumentException("Corrupt parameter: " + paramName
// + " in feature " + name, e);
// }
// }
public int getValueTimeout() throws IllegalArgumentException{
final String paramName = "Value_Timeout";
try{
int valueTimeout = Integer.parseInt(params.get(paramName)) * 1000;
if (valueTimeout <= 0){
throw new IllegalArgumentException("Must be a positive integer");
}
return valueTimeout;
}catch(Exception e){// NullPointer or Parsing
throw new IllegalArgumentException("Corrupt parameter: " + paramName
+ " in feature " + name, e);
}
}
public double getMovieAverageWeight() throws IllegalArgumentException{
final String paramName = "Moving_Average_Weight";
try{
double movingAverageWeight = Double.parseDouble(params.get(paramName));
if (movingAverageWeight < 0 || movingAverageWeight > 1){
throw new IllegalArgumentException("Must be positive and 1.0 at most");
}
return movingAverageWeight;
}catch(Exception e){// NullPointer or Parsing
throw new IllegalArgumentException("Corrupt parameter: " + paramName
+ " in feature " + name, e);
}
}
public boolean getIncludeEventTimes(){
final String paramName = "Include_Event_Times";
return Boolean.parseBoolean(params
.get(paramName));
}
public boolean getIncludeMaximalEntity(){
final String paramName = "Include_Maximal_Entity";
return Boolean.parseBoolean(params
.get(paramName));
}
}
MonitoredData.java
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
#SuppressWarnings("unchecked")
public class MonitoredData implements Map, Parcelable{
public static final int DEFAULT = 0;
public static final int HAS_EXTRAS = 1;
protected String _name;
protected ParcelableDate _startTime, _endTime;
protected Object _value;
protected Bundle _extras;
public static final Parcelable.Creator<MonitoredData> CREATOR = new Parcelable.Creator<MonitoredData>(){
public MonitoredData createFromParcel(Parcel in){
ClassLoader cl = ParcelableDate.class.getClassLoader();
String name = in.readString();
Object value = in.readValue(null);
ParcelableDate startTime = (ParcelableDate)in.readParcelable(cl);
ParcelableDate endTime = (ParcelableDate)in.readParcelable(cl);
Bundle extras = in.readBundle();
MonitoredData monitoredData = new MonitoredData(name, value, startTime,
endTime);
if (extras != null){
monitoredData.setExtras(extras);
}
return monitoredData;
}
public MonitoredData[] newArray(int size){
return new MonitoredData[size];
}
};
private static DateFormat _sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
public MonitoredData(String name, Object value, Date endTime){
this(name, value, new ParcelableDate(endTime), new ParcelableDate(endTime));
}
public MonitoredData(String name, Object value, ParcelableDate endTime){
this(name, value, endTime, endTime);
}
public MonitoredData(String name, Object value, Date startTime, Date endTime){
this(name, value, new ParcelableDate(startTime), new ParcelableDate(endTime));
}
public MonitoredData(String name, Object value, Date startTime, ParcelableDate endTime){
this(name, value, new ParcelableDate(startTime), endTime);
}
public MonitoredData(String name, Object value, ParcelableDate startTime,
ParcelableDate endTime){
_name = name;
_startTime = startTime;
_endTime = endTime;
_value = value;
_extras = null;
}
public void setExtras(Bundle extras){
_extras = extras;
}
public Map<String, Object> toMap(){
TreeMap<String, Object> map = new TreeMap<String, Object>();
map.put("Name", _name);
map.put("StartTime", _startTime);
map.put("EndTime", _endTime);
map.put("Value", _value);
return map;
}
public String conciseToString(){
String extrasToString = (_extras != null && !_extras.isEmpty()) ? " - "
+ _extras.toString() : "";
return "{" + getName() + " = " + getValue() + "}" + extrasToString;
}
public int describeContents(){
return (_extras == null || _extras.isEmpty()) ? DEFAULT : HAS_EXTRAS;
}
public ParcelableDate getEndTime(){
return _endTime;
}
public String getName(){
return _name;
}
public ParcelableDate getStartTime(){
return _startTime;
}
public Object getValue(){
return _value;
}
public Bundle getExtras(){
return _extras;
}
public String toString(){
StringBuilder sb = new StringBuilder("{");
sb.append("Name = " + getName() + ", ");
sb.append("Value = " + getValue() + ", ");
sb.append("StartTime = " + _sdf.format(getStartTime()) + ", ");
sb.append("EndTime = " + _sdf.format(getEndTime()));
sb.append("}");
return sb.toString();
}
public void writeToParcel(Parcel dest, int flags){
dest.writeString(getName());
dest.writeValue(getValue());
dest.writeParcelable(getStartTime(), 0);
dest.writeParcelable(getEndTime(), 0);
dest.writeBundle(_extras);
}
public void clear(){
throw new UnsupportedOperationException();
}
public boolean containsKey(Object key){
throw new UnsupportedOperationException();
}
public boolean containsValue(Object value){
throw new UnsupportedOperationException();
}
public Set entrySet(){
return Collections.unmodifiableSet(toMap().entrySet());
}
public Object get(Object key){
throw new UnsupportedOperationException();
}
public boolean isEmpty(){
throw new UnsupportedOperationException();
}
public Set keySet(){
throw new UnsupportedOperationException();
}
public Object put(Object key, Object value){
throw new UnsupportedOperationException();
}
public void putAll(Map arg0){
throw new UnsupportedOperationException();
}
public Object remove(Object key){
throw new UnsupportedOperationException();
}
public int size(){
throw new UnsupportedOperationException();
}
public Collection values(){
throw new UnsupportedOperationException();
}
/**
* Returns the value of the monitored data as a Double.
* Null is returned if the value is null or is can not be converted to double.
*
* #return The value as double if possible, null otherwise
*/
public Double mdToDouble(){
Double sample;
Object val = getValue();
if (val instanceof Double){
sample = ((Double)val).doubleValue();
}else if (val instanceof Long){
sample = ((Long)val).doubleValue();
}else if (val instanceof Integer){
sample = ((Integer)val).doubleValue();
}else{
sample = null;
}
return sample;
}
}
Utils.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Formatter;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.content.Context;
import android.content.res.Resources;
import android.os.Environment;
import android.widget.Toast;
public class Utils{
public static byte[] append(byte[] first, byte[] second){
byte[] bytes;
bytes = new byte[first.length + second.length];
System.arraycopy(first, 0, bytes, 0, first.length);
System.arraycopy(second, 0, bytes, first.length, second.length);
return bytes;
}
public static int bytesToInt(byte[] bytes){
return (bytes[3] & 0xFF) | ((bytes[2] & 0xFF) << 8) | ((bytes[1] & 0xFF) << 16)
| ((bytes[0] & 0xFF) << 24);
}
public static int littleEndianBytesToInt(byte[] bytes){
return (bytes[0] & 0xFF) | ((bytes[1] & 0xFF) << 8) | ((bytes[2] & 0xFF) << 16)
| ((bytes[3] & 0xFF) << 24);
}
public static long littleEndianBytesToUShort(byte[] arr){
return (arr[1] << 8) | arr[0];
}
public static void displayShortAlert(Context context, String message){
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
public static XmlPullParser getXPP(Context context, int resourceId, boolean isBinary){
XmlPullParser xpp;
Resources resources = context.getResources();
if (isBinary){
return resources.getXml(resourceId);
}else{
try{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
xpp = factory.newPullParser();
xpp.setInput(resources.openRawResource(resourceId), null);
}catch(XmlPullParserException e){
xpp = null;
}
return xpp;
}
}
public static byte[] intToBytes(int i){
byte[] bytes = new byte[]{(byte)((i >> 24) & 0xff), (byte)((i >> 16) & 0xff),
(byte)((i >> 8) & 0xff), (byte)((i) & 0xff)};
return bytes;
}
/*
* debugging
*/
public static String printByteArray(byte[] bytes, int len){
StringBuilder sb = new StringBuilder();
sb.append("msg len: " + len + " :");
Formatter f = new Formatter(sb);
for (int i = 0; i < len; i++){
f.format("%2x", bytes[i]);
}
sb.append("\n");
return sb.toString();
}
public static List<Integer> getPids(String fileName){
String line;
int pidIndex = -1;
try{
Process p = Runtime.getRuntime().exec("ps " + fileName);
p.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()), 256);
if ((line = br.readLine()) == null){
throw new IllegalStateException("Unable to read ps output");
}
String[] tokens = line.split(" +");
for (int i = 0; i < tokens.length; ++i){
if (tokens[i].equalsIgnoreCase("pid")){
pidIndex = i;
}
}
if (pidIndex < 0){
throw new IllegalStateException("Unable to locate pid field in ps output");
}
List<Integer> pids = new ArrayList<Integer>();
while ((line = br.readLine()) != null){
tokens = line.split(" +");
assert tokens.length < 9;
try{
pids.add(Integer.parseInt(tokens[pidIndex]));
}catch(NumberFormatException e){
throw new IllegalStateException("Pid is not an integer");
}
}
br.close();
return pids;
}catch(Exception e){
throw new IllegalStateException("Unable to read running process through ps: "
+ e.getMessage(), e);
}
}
public static void killProcesses(List<Integer> pids){
for (Integer pid : pids){
android.os.Process.killProcess(pid);
}
}
public static void killProcesses(String processName){
killProcesses(getPids(processName));
}
public static void suKillProcesses(List<Integer> pids){
StringBuilder cmd = new StringBuilder("kill");
for (Integer pid : pids){
cmd.append(" ").append(pid);
}
try{
Runtime.getRuntime().exec(new String[]{"su", "-c", cmd.toString()});
}catch(IOException e){
e.printStackTrace();
}
}
public static void suKillProcess(int pid){
try{
Runtime.getRuntime().exec(new String[]{"su", "-c", "kill " + pid});
}catch(IOException e){
e.printStackTrace();
}
}
public static void suKillProcesses(String processName){
suKillProcesses(getPids(processName));
}
public static double truncateDouble(double d){
long l = Math.round(d * 100);
return l / 100.0;
}
public static double calcMovingAvg(double oldVal, double newVal, double newValWeight){
return (oldVal * (1.0 - newValWeight)) + (newValWeight * newVal);
}
public static double calcAvg(double oldAvg, int count, double newVal){
return (oldAvg * count + newVal) / (count + 1);
}
public static void writeLogToFile(Context context, boolean onSdcard, String prefix, int timeWindowInSeconds) throws Exception{
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss");
final DateFormat logDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
final long currentTime = System.currentTimeMillis();
final long startTime = currentTime - timeWindowInSeconds * 1000;
final String currentYear = Calendar.getInstance().get(Calendar.YEAR) + "-";
final String logFileName = prefix + sdf.format(new Date(currentTime)) + ".log";
BufferedReader logcatIn;
Process logcat;
OutputStream logFile;
try{
logcat = Runtime.getRuntime().exec("logcat -v time -d *:d");
logcatIn = new BufferedReader(new InputStreamReader(logcat
.getInputStream()), 1024);
}catch(IOException e){
throw new Exception("Unable to launch logcat: " + e.getMessage(), e);
}
try{
if (onSdcard){
logFile = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), logFileName));
}else{
logFile = context.openFileOutput(logFileName, 0);
}
}catch(IOException e){
throw new Exception("Unable to create log file: " + e.getMessage(), e);
}
PrintWriter pw = new PrintWriter(logFile, false);
String line;
long logLineTime;
while ((line = logcatIn.readLine()) != null){
logLineTime = logDF.parse(currentYear + line.substring(0, line.indexOf(".") + 4)).getTime();
if (logLineTime >= startTime){
pw.println(line);
}
}
pw.flush();
pw.close();
logcatIn.close();
logcat.destroy();
}
}
FeatureExtractor.java
import java.util.List;
/**
* A class capable of extracting one or more features. It MUST have a public constructor
* with the following parameters in this order:
* <ul>
* <li>Context context</li>
* <li>Collection<FeatureInfo> featureInfos</li>
* <li>Long timeStamp</li>
* </ul>
*
*/
public interface FeatureExtractor{
/**
* Invoked during a data collection. It is up to the extractor to add the data
* relevant to it's monitored features to the monitoredData list.
*
* #param monitoredData The overall collected data (from all extractors) so far
* #param endTime The time of the current data collection
*/
public void collectData(List<MonitoredData> monitoredData, ParcelableDate endTime);
/**
* Invoked when the feature extractor is no longer needed. This is the place to
* release any resources, unregister any listeners, close any threads, etc.
*/
public void close();
}
FeatureExtractorInitException.java
public class FeatureExtractorInitException extends RuntimeException{
private static final long serialVersionUID = 1L;
public FeatureExtractorInitException(String message){
super(message);
}
public FeatureExtractorInitException(String message, Throwable t){
super(message, t);
}
public FeatureExtractorInitException(Throwable t){
super(t);
}
}
For example if you had an imageView one way of fetching coordinates is...
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
int[] values = new int[2];
view.getLocationOnScreen(values);
Log.d("X & Y",values[0]+" "+values[1]);
}
});
Check out these ST threads:
How to get imageView inside onTouchEvent(MotionEvent event) in android
Android: How do I get the x y coordinates within an image / ImageView?
OnClickListener - x,y location of event?
Find layout with x,y coordinate
If you use reuf codes,you will need to use ParcelableData.java.I add ParcelableData class that found here and hope to save your time:
package dev.drsoran.moloko.service.parcel;
import java.util.Date;
import android.os.Parcel;
import android.os.Parcelable;
public class ParcelableDate implements Parcelable
{
public static final Parcelable.Creator< ParcelableDate > CREATOR = new Parcelable.Creator< ParcelableDate >()
{
public ParcelableDate createFromParcel( Parcel source )
{
return new ParcelableDate( source );
}
public ParcelableDate[] newArray( int size )
{
return new ParcelableDate[ size ];
}
};
private final Date date;
public ParcelableDate( final Date date )
{
this.date = date;
}
public ParcelableDate( long millis )
{
this.date = new Date( millis );
}
public ParcelableDate( Parcel source )
{
date = new Date( source.readLong() );
}
public Date getDate()
{
return date;
}
#Override
public String toString()
{
return date.toString();
}
public int describeContents()
{
return 0;
}
public void writeToParcel( Parcel dest, int flags )
{
dest.writeLong( date.getTime() );
}
}

Categories

Resources