Data management outputted from a transaction - blockchain

I have a smart contract in which I simulate an event through a set that manually inputs certain data like this: (I use Remix)
[ "From", "to", "object", [ "rules1", "rules2"]], [[1, "data1"], [2, "data2"], [3, "data3"]]
This is my code:
pragma experimental "v0.5.0";
pragma experimental ABIEncoderV2;
contract StructContract {
struct Certificate{
uint id;
string data;
}
struct StructEvent {
string _from;
string _to;
string _object;
string[] _rules;
}
StructEvent structEvent;
Certificate[] certificate;
function setEvent(StructEvent eventS,Certificate[] eventC) public{
certificate.length=0;
structEvent = eventS;
for(uint i=0;i<(eventC.length);i++){
certificate.push(Certificate(eventC[i].id,eventC[i].data));
}
}
function getStruct() view public returns(StructEvent){
return(structEvent);
}
function getCertificate() view public returns(Certificate[]){
return(certificate);
}
function returnAllData() view public returns(StructEvent,Certificate[]){
return(structEvent,certificate);
}
}
once this is done, what I expect is that these data are put into a transaction that is then uploaded to blockchain. Then I have to take the data in these transactions to perform checks on them.
So I need to have data that are put on blockchain, as a solution to this problem I created this code: (I use web3 1.0.0-beta.36)
function printTransaction(txHash) {
web3.eth.getTransaction(txHash, function (error, tx) {
if (tx != null) {
var inputData = tx.input;
try {
var myContract = new web3.eth.Contract(abi, tx.to);
var result = web3.eth.abi.decodeParameters(['tuple(string,string,string,string[])',
'tuple(uint,string)[]'], inputData.slice(10));
var data1 = result[0];
var data2 = result[1];
console.log("\n\n");
console.log("--- transactions ---");
console.log(" tx hash : " + tx.hash + "\n"
+ " nonce : " + tx.nonce + "\n"
+ " blockHash : " + tx.blockHash + "\n"
+ " blockNumber : " + tx.blockNumber + "\n"
+ " transactionIndex: " + tx.transactionIndex + "\n"
+ " from : " + tx.from + "\n"
+ " to : " + tx.to + "\n"
+ " value : " + tx.value + "\n"
+ " gasPrice : " + tx.gasPrice + "\n"
+ " gas : " + tx.gas + "\n"
+ " input : " + tx.input + "\n"
+ " decodeinput : " + "\n"
+ " Struct : " + data1 + "\n"
+ " Certificates : " + data2);
web3.eth.getAccounts(function (err, account) {
myContract.methods.setEvent(data1, data2).send({ from: account[0], gas: 3000000 }, function (err, resul) {
if (err) {
console.log("err");
} else {
console.log("\n\n");
console.log("--- data ---");
myContract.methods.returnAllData().call().then(console.log);
}
});
});
} catch (Error) { }
}
});
}
What I decided to do is create, in a js file, a method that was able to take the transactions, decode the input related to the data contained in it and pass this data, through the send, to my smart contract in which it will be used.
these methods that I created represent the right solution? or I have to use another kind of approach, another method to do this?
Thanks in advance.

Related

AWS adaptor with Spring Cloud function - payload body is removed

I am building a AWS lambda function using Spring cloud, aws adapter and spring native.
The lambda is fronted by a APIGateway HTTP API V2.0.
<java.version>11</java.version>
<spring-cloud.version>2021.0.2</spring-cloud.version>
<spring-native.version>0.11.4</spring-native.version>
<aws-lambda-events.version>3.9.0</aws-lambda-events.version>
<wrapper.version>1.0.27.RELEASE</wrapper.version>here
When I hit the API with the cloud function pointing to echo function, I get a response with the body of the request removed!
I setup below test to debug the issue. Found that the below highlighted code from
org.springframework.cloud.function.adapter.aws.AWSLambdaUtils
is causing the issue. I see that the highlighted line is removed in the 4X branch. Request to kindly guide how to incorporate that fix into my project while staying on the release version of the dependencies.
public static void main(String[] args) {
String message = "{\r\n"
+ " \"version\": \"2.0\",\r\n"
+ " \"routeKey\": \"POST /updatePet\",\r\n"
+ " \"rawPath\": \"/updatePet\",\r\n"
+ " \"rawQueryString\": \"\",\r\n"
+ " \"headers\": {\r\n"
+ " \"accept\": \"*/*\",\r\n"
+ " \"accept-encoding\": \"gzip, deflate, br\",\r\n"
+ " \"content-length\": \"77\",\r\n"
+ " \"content-type\": \"application/json\",\r\n"
+ " \"host\": \"XXXXXX.execute-api.ap-south-1.amazonaws.com\",\r\n"
+ " \"postman-token\": \"2004009f-2661-46ea-9a31-2d6be0bb9281\",\r\n"
+ " \"user-agent\": \"PostmanRuntime/7.29.0\",\r\n"
+ " \"x-amzn-trace-id\": \"Root=1-62823410-XXXXXXXXXXXXX\",\r\n"
+ " \"x-forwarded-for\": \"111.11.111.111, 111.111.111.111\",\r\n"
+ " \"x-forwarded-port\": \"443\",\r\n"
+ " \"x-forwarded-proto\": \"https\"\r\n"
+ " },\r\n"
+ " \"requestContext\": {\r\n"
+ " \"accountId\": \"123456733\",\r\n"
+ " \"apiId\": \"xxxxx\",\r\n"
+ " \"domainName\": \"xxxxxx.execute-api.ap-south-1.amazonaws.com\",\r\n"
+ " \"domainPrefix\": \"vaoo36b2l5\",\r\n"
+ " \"http\": {\r\n"
+ " \"method\": \"POST\",\r\n"
+ " \"path\": \"/updatePet\",\r\n"
+ " \"protocol\": \"HTTP/1.1\",\r\n"
+ " \"sourceIp\": \"1.1.1.1\",\r\n"
+ " \"userAgent\": \"PostmanRuntime/7.29.0\"\r\n"
+ " },\r\n"
+ " \"requestId\": \"SN0SoioabccwEJuQ=\",\r\n"
+ " \"routeKey\": \"POST /updatePet\",\r\n"
+ " \"stage\": \"$default\",\r\n"
+ " \"time\": \"16/May/2022:11:22:56 +0000\",\r\n"
+ " \"timeEpoch\": 1652700176657\r\n"
+ " },\r\n"
+ " \"body\": \"{\\r\\n\\\"id\\\":1,\\r\\n\\\"name\\\":\\\"toto\\\",\\r\\n\\\"type\\\":\\\"dog\\\",\\r\\n\\\"owner\\\":{\\\"name\\\":\\\"test\\\",\\\"age\\\":8}\\r\\n}\",\r\n"
+ " \"isBase64Encoded\": false\r\n"
+ "}";
Message<byte[]> msg = AWSLambdaUtils.generateMessage(message.getBytes(StandardCharsets.UTF_8), headers(), String.class, mapper());
var payload = new String(msg.getPayload(),StandardCharsets.UTF_8);
System.out.println("payload is"+payload);
}

Unable to search data in autocompletetextview in fragment and unable to open fragment

Error : Unable to Open Fragment
DBHelper.SelectAllDataView(java.lang.String, java.lang.String)' on a
null object reference at
com.example.venkateshbm.myapplication.OpeningStockFragment.onCreateView(OpeningStockFragment.java:38)
at
android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
at
android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
Fragment Code:
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
public class OpeningStockFragment extends Fragment {
DBHelper mydb;
Button btnlsubmit;
EditText fret_expdate,fretbatchno;
AutoCompleteTextView fracproductname;
public static OpeningStockFragment newInstance(){
return new OpeningStockFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_opening_stock,container,false);
fracproductname = (AutoCompleteTextView) v.findViewById(R.id.ac_productname);
fret_expdate = (EditText) v.findViewById(R.id.fr_et_expdate);
fretbatchno = (EditText)v.findViewById(R.id.fr_ac_batchno);
Context c = getActivity().getApplicationContext();
final String[] myproductname = mydb.SelectAllDataView(DBHelper.ITEM_TABLE, DBHelper.ITEM_NAME);
ArrayAdapter<String> aaproductname = new ArrayAdapter<String>(c, android.R.layout.simple_dropdown_item_1line, myproductname);
fracproductname.setAdapter(aaproductname);
fracproductname.setThreshold(1);
fret_expdate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean b) {
if ( b) {
Datedialog datedialog= new Datedialog(view);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
datedialog.show(getActivity().getFragmentManager(),"DatePicker");
}
}
});
return v;
}
}
DBHelper Class:
package com.example.venkateshbm.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.wifi.aware.PublishConfig;
import android.util.Log;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
/**
* Created by venkatesh on 10/10/17.
*/
public class DBHelper extends SQLiteOpenHelper {
/** Item Master Table FIELDS DEFINE */
public SQLiteDatabase sqliteDBInstance =null;
public static final String DATABASE_NAME = "pharmacy.db";
public static final String ITEM_TABLE = "item_mst";
public static final String ITEM_CODE = "item_code";
public static final String ITEM_NAME = "item_name";
public static final String ITEM_PACK = "item_pack";
public static final String ITEM_PACK_CONV = "item_pack_conv";
public static final String BAR_CODE = "bar_code";
public static final String MANF_CODE = "manf_code";
public static final String CATG_CODE = "catg_code";
public static final String CONT_CODE = "cont_code";
public static final String ITEM_DISC = "item_disc";
public static final String GST_PERCE = "gst_perce";
public static final String ITEM_RACK = "item_rack";
public static final String ITEM_SHELF = "item_shelf";
public static final String ITEM_DATE = "item_date";
public static final String TIME_STAMP = "item_stamp";
public static final String ITEM_LBNO = "item_lbno";
public static final String ITEM_LMRP = "item_lmrp";
public static final String ITEM_MINLVL = "item_minlvl";
public static final String ITEM_MAXLVL = "item_maxlvl";
public static final String SCHE_DRUG = "sche_drug";
public static final String HSN_CODE = "hsn_code";
public static final String ITEM_FLAG = "item_flag";
/** Manufacture Master Tabble Fields DEFINE */
public static final String MANF_TABLE_NAME = "manufacture_mst";
public static final String C_CODE = "c_code";
public static final String C_NAME = "c_name";
public static final String C_ADD1 = "c_add1";
public static final String C_ADD2 = "c_add2";
public static final String C_ADD3 = "c_add3";
public static final String C_CITY = "c_city";
public static final String C_PIN = "c_pin";
public static final String C_PH1 = "c_ph1";
public static final String C_PH2 = "c_ph2";
public static final String C_CONTACT = "c_contact";
public static final String C_DL1 = "c_dl1";
public static final String C_DL2 = "c_dl2";
public static final String C_GSTNO = "c_gstno";
public static final String C_SHORT = "c_short";
public static final String C_LOCK = "c_lock";
public static final String C_USER = "c_user";
public static final String C_C_DATE = "c_c_date";
public static final String C_M_DATE = "c_m_date";
// TAX MASTER TABLE FIELDS DEFINE
public static final String TAX_TABLE = "tax_master";
public static final String TAX_CODE = "tax_code";
public static final String TAX_NAME = "tax_name";
public static final String TAX_CGST = "tax_cgst";
public static final String TAX_SGST = "tax_sgst";
public static final String TAX_IGST = "tax_igst";
public static final String TAX_ON_SCH = "tax_on_sch";
public static final String TAX_ON_MRP = "tax_on_mrp";
// PRODUCT CATOGERY TABLE FIELDS DEFINE
public static final String CATG_MASTER = "catg_master";
public static final String CATG_CODE1 = "cat_code";
public static final String CATG_NAME = "catg_name";
// CONTENT MASTER TABLE FIELDS DEFINE
public static final String CONT_MASTER = "cont_master";
public static final String CONT_CODE1 = "cont_code";
public static final String CONT_NAME = "cont_name";
public static final String CONT_SHORT = "cont_short";
// PACKING MASTER TABLE FIELDS DEFINE
public static final String PACK_MASTER = "pack_master";
public static final String PACK_CODE = "pack_code";
public static final String PACK_NAME = "pack_name";
public static final String PACK_CONV = "pack_conv";
// SCHEDULED TABLE FIELD DEFINE
public static final String SCHEDULE_MASTER = "schedule_master";
public static final String S_CODE = "s_code";
public static final String S_NAME = "s_name";
public static final String S_MSG = "s_msg";
// USER TABLE FIELD DEFINE
public static final String TABLE_USER = "user_mst";
public static final String USER_ID = "user_id";
public static final String USER_NAME = "user_name";
public static final String USER_PWD = "user_pwd";
public static final String USER_TYPE = "user_type";
public static final String USER_CREATE_DATE = "user_create_date";
public static final String USER_ROLES = "user_roles";
public static final String USER_EDIT_DATE = "user_edit_date";
// OPENING STOCK TABLE FIELD DEFINE
public static final String OPENING_STOCK_MST = "opening_stock_mst";
public static final String OPEN_STK_CODE = "open_stk_code";
public static final String OPEN_BATCH_ID = "open_batch_id";
public static final String OPEN_USER_ID = "open_user_id";
public static final String OPEN_STK_DATE = "open_stk_date";
public static final String OPEN_EDIT_DATE = "open_edit_date";
public static final String OPEN_STK_QTY = "open_stk_qty";
public static final String OPEN_STK_MRP = "open_stk_mrp";
public static final String OPEN_STK_PTR = "open_stk_ptr";
public static final String OPEN_SUP_CODE = "open_sup_code";
// STOCK MASTER TABLE FIELD DEFINE
public static final String TABLE_STOCK = "stock";
public static final String STOCK_ID = "stock_id";
public static final String STK_ITEM_CODE = "stk_item_code";
public static final String STK_BATCH_ID = "stk_batch_id";
public static final String OPENING_STOCK = "opening_stock";
public static final String STOCK_MRP = "stock_mrp";
public static final String STOCK_PTR = "stock_ptr";
public static final String STOCK_EXPIRY = "stock_expiry";
public static final String STOCK_MONTH = "stock_month";
public static final String SALES_QTY = "sales_qty";
public static final String SALES_FQTY = "sales_fqty";
public static final String ADJT_QTY = "adju_qty";
public static final String BALC_QTY = "balc_qty";
public static final String STOCK_GST = "stock_gst";
public static final String EDIT_DATE = "edit_date";
public static final String STOCK_USER_ID = "stock_user_id";
public static final String STK_SUP_CODE = "stk_sup_code";
// BATCH MASTER TABLE FIELD DEFINE
public static final String TABLE_BATCH = "batch_mst";
public static final String BATCH_ID = "batch_id";
public static final String BAT_ITEM_CODE = "bat_item_code";
public static final String BATCH_NO = "batch_no";
public static final String MANF_DATE = "manf_date";
public static final String EXPI_DATE = "expi_date";
public static final String TRANS_TYPE = "trans_type";
public static final String RECV_QTY = "recv_qty";
public static final String RECV_FQTY = "recv_fqty";
public static final String RECV_DATE = "recv_date";
public static final String SUP_CODE = "sup_code";
public static final String BATCH_MRP = "batch_mrp";
public static final String BATCH_PTR = "batch_ptr";
public static final String BATCH_DISC = "batch_disc";
public static final String BATCH_GST = "batch_gst";
public static final String BATCH_USER_ID = "batch_user_id";
private static DBHelper instance;
public static synchronized DBHelper getHelper(Context context) {
if(instance == null) {
instance = new DBHelper(context);
}
return instance;
}
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
}
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
if(!db.isReadOnly()) {
db.execSQL("PRAGMA foreign_keys = 'ON' ;");
}
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL( " create table " + TABLE_BATCH
+ " ( "
+ BATCH_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ BATCH_NO + " VARCHAR2(20) ,"
+ BAT_ITEM_CODE + " INTEGER ,"
+ MANF_DATE + " DATE ,"
+ EXPI_DATE + " DATE ,"
+ TRANS_TYPE + " VARCHAR2(5) ,"
+ RECV_DATE + " DATE ,"
+ RECV_QTY + " INTEGER ,"
+ RECV_FQTY + " INTEGER ,"
+ SUP_CODE + " VARCHAR(10) ,"
+ BATCH_MRP + " NUMERIC(7,2) ,"
+ BATCH_PTR + " NUMERIC(7,2) ,"
+ BATCH_DISC + " NUMERIC(5,2) ,"
+ BATCH_GST + " INTEGER ,"
+ BATCH_USER_ID + " INTEGER )" );
sqLiteDatabase.execSQL(" create table " + TABLE_STOCK
+ " ( "
+ STOCK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ STK_ITEM_CODE + " INTEGER ,"
+ STK_BATCH_ID + " INTEGER ,"
+ OPENING_STOCK + " INTEGER ,"
+ STOCK_MRP + " NUMERIC(7,2) ,"
+ STOCK_PTR + " NUMERIC(7,2) ,"
+ STOCK_EXPIRY + " DATE ,"
+ STOCK_MONTH + " VARCHAR2(15) ,"
+ SALES_QTY + " INTEGER ,"
+ SALES_FQTY + " INTEGER ,"
+ ADJT_QTY + " INTEGER ,"
+ BALC_QTY + " INTEGER ,"
+ STOCK_GST + " INTEGER ,"
+ EDIT_DATE + " DATE ,"
+ STOCK_USER_ID + " INTEGER ,"
+ STK_SUP_CODE + " VARCHAR2(10) )" );
sqLiteDatabase.execSQL(" create table " + OPENING_STOCK_MST
+ " ( "
+ OPEN_STK_CODE + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ OPEN_BATCH_ID + " VARCHAR2(15) ,"
+ OPEN_USER_ID + " INTEGER ,"
+ OPEN_STK_DATE + " DATE ,"
+ OPEN_EDIT_DATE + " DATE ,"
+ OPEN_STK_QTY + " INTEGER ,"
+ OPEN_STK_MRP + " NUMERIC(7,2) ,"
+ OPEN_STK_PTR + " NUMERIC(7,2) ,"
+ OPEN_SUP_CODE + " VARCHAR2(10) )"
);
sqLiteDatabase.execSQL(" create table " + TABLE_USER
+ "( "
+ USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ USER_NAME + " VARCHAR2(30) ,"
+ USER_PWD + " VARCHAR2(50) ,"
+ USER_TYPE + " VARCHAR2(30) ,"
+ USER_CREATE_DATE + " DATE ,"
+ USER_ROLES + " INTEGER ,"
+ USER_EDIT_DATE + " DATE )"
);
sqLiteDatabase.execSQL(" create table " + MANF_TABLE_NAME
+ " ( "
+ C_CODE + " VARCHAR(10) PRIMARY KEY ,"
+ C_NAME + " VARCHAR(100) ,"
+ C_ADD1 + " VARCHAR(60) ,"
+ C_ADD2 + " VARCHAR(60) ,"
+ C_ADD3 + " VARCHAR(60) ,"
+ C_CITY + " VARCHAR(30) ,"
+ C_PIN + " INTEGER ,"
+ C_PH1 + " NUMBER (10) ,"
+ C_PH2 + " NUMBER (10) ,"
+ C_CONTACT + " VARCHAR(25) ,"
+ C_DL1 + " VARCHAR(40) ,"
+ C_DL2 + " VARCHAR(40) ,"
+ C_GSTNO + " VARCHAR(15) ,"
+ C_SHORT + " VARCHAR(6) ,"
+ C_LOCK + " CHAR(1) ,"
+ C_USER + " VARCHAR(15) ,"
+ C_C_DATE + " DATE ,"
+ C_M_DATE + " DATE );" );
sqLiteDatabase.execSQL( " create table " + ITEM_TABLE
+ " ( "
+ ITEM_CODE + " varchar(10) primary key , "
+ ITEM_NAME + " varchar(50) ,"
+ ITEM_PACK + " varchar(10) ,"
+ ITEM_PACK_CONV + " INTEGER ,"
+ BAR_CODE + " varchar(20) ,"
+ MANF_CODE + " VARCHAR(10) ,"
+ CATG_CODE + " VARCHAR(6) ,"
+ CONT_CODE + " VARCHAR(10) ,"
+ ITEM_DISC + " NUMERIC(5,2) ,"
+ GST_PERCE + " INTEGER ,"
+ ITEM_RACK + " varchar(5) ,"
+ ITEM_SHELF + " varchar(5) ,"
+ TIME_STAMP + " text , "
+ ITEM_LBNO + " varchar(15) ,"
+ ITEM_LMRP + " NUMERIC(12,2) ,"
+ ITEM_MINLVL + " INTEGER ,"
+ ITEM_MAXLVL + " INTEGER ,"
+ SCHE_DRUG + " varchar(6) ,"
+ HSN_CODE + " varchar(10) ,"
+ ITEM_FLAG + " char(1) );" );
// TAX MASTER TABLE CREATION
sqLiteDatabase.execSQL( "create table " + TAX_TABLE + "("
+ TAX_CODE + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ TAX_NAME + " VARCHAR(10) ,"
+ TAX_CGST + " NUMERIC(5,2) ,"
+ TAX_SGST + " NUMERIC(5,2) ,"
+ TAX_IGST + " NUMERIC(5,2) ,"
+ TAX_ON_SCH + " CHAR(1) ,"
+ TAX_ON_MRP + " CHAR(1) )" );
Log.d( " TAX TABLE CREATION" , "Successfully Tax Table Created ");
// PRODUCT CATOGERY TABLE CREATION
sqLiteDatabase.execSQL( "create table " + CATG_MASTER + " ( "
+ CATG_CODE1 + " VARCHAR(6) PRIMARY KEY ,"
+ CATG_NAME + " VARCHAR(30) )" );
// CONTENT MASTER TABLE CREATION
sqLiteDatabase.execSQL( "create table " + CONT_MASTER + " ( "
+ CONT_CODE1 + " VARCHAR(10) PRIMARY KEY ,"
+ CONT_NAME + " VARCHAR2(128) ,"
+ CONT_SHORT + " VARCHAR2(4) )"
);
// PACKING MASTER TABLE CREATEION
sqLiteDatabase.execSQL(" create table " + PACK_MASTER + "("
+ PACK_CODE + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ PACK_NAME + " VARCHAR2(10) ,"
+ PACK_CONV + " INTEGER )" );
sqLiteDatabase.execSQL(" create table " + SCHEDULE_MASTER + " ("
+ S_CODE + " varchar(5) primary key ,"
+ S_NAME + " varchar(30) ,"
+ S_MSG + " varchar(60))"
);
}
// sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
// onCreate(sqLiteDatabase);
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("Drop table if exists " + ITEM_TABLE);
sqLiteDatabase.execSQL("drop table if exists " + MANF_TABLE_NAME);
sqLiteDatabase.execSQL("drop table if exists " + TAX_TABLE);
sqLiteDatabase.execSQL("drop table if exists " + CATG_MASTER);
sqLiteDatabase.execSQL("drop table if exists " + CONT_MASTER);
sqLiteDatabase.execSQL("drop table if exists " + PACK_MASTER);
sqLiteDatabase.execSQL("drop table if exists " + SCHEDULE_MASTER);
onCreate(sqLiteDatabase);
Log.d("Database Created", " Created table successfull" + ITEM_TABLE + " " + MANF_TABLE_NAME);
}
public boolean insert_data(Integer itemcode, String itemname, String itempack, Integer itempackconv, String barcode, String manfcode,
String catgcode, String contcode, Double itemdisc, int gstperce, String itemrack, String itemshelf,
String timestamp, String itemlbno, Double itemlmrp, Integer itemminlvl, Integer itemmaxlvl, String schedrug,
String hsncode, String itemflag) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(ITEM_CODE,itemcode);
contentValues.put(ITEM_NAME,itemname);
contentValues.put(ITEM_PACK,itempack);
contentValues.put(ITEM_PACK_CONV,itempackconv);
contentValues.put(BAR_CODE,barcode);
contentValues.put(MANF_CODE,manfcode);
contentValues.put(CATG_CODE,catgcode);
contentValues.put(CONT_CODE,contcode);
contentValues.put(ITEM_DISC,itemdisc);
contentValues.put(GST_PERCE,gstperce);
contentValues.put(ITEM_RACK,itemrack);
contentValues.put(ITEM_SHELF,itemshelf);
contentValues.put(TIME_STAMP,timestamp);
contentValues.put(ITEM_LBNO,itemlbno);
contentValues.put(ITEM_LMRP,itemlmrp);
contentValues.put(ITEM_MINLVL,itemminlvl);
contentValues.put(ITEM_MAXLVL,itemmaxlvl);
contentValues.put(SCHE_DRUG, schedrug);
contentValues.put(HSN_CODE,hsncode);
contentValues.put(ITEM_FLAG,itemflag);
db.insert(ITEM_TABLE,null,contentValues);
return true;
}
public Cursor getData(String itemcode) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor resu = db.rawQuery("select * from ITem_MST where item_code = " + itemcode + "",null);
return resu;
}
public String[] SelectAllData(String TABLE_NAME , String ITEMNAME, String ITEMCODE){
SQLiteDatabase db = this.getReadableDatabase();
// Cursor cursor =db.query(TABLE_NAME,null, null,null,null,null,null);
Cursor cursor = db.query(TABLE_NAME, new String[]{ITEMNAME,ITEMCODE},null,null,null,null,null);
Log.i("DataBase Count","Total Records" + cursor.getCount());
if ( cursor.getCount() >0 )
{
String[] arrData = new String[cursor.getCount()];
int i = 0 ;
while (cursor.moveToNext())
{
arrData[i]=cursor.getString(cursor.getColumnIndex(ITEMNAME)) + " CODE: " +cursor.getString(cursor.getColumnIndex(ITEMCODE)) ;
i++;
}
return arrData;
}
else
{
return new String[] {};
}
}
public String[] SelectAllDataView(String TABLE_NAME , String ITEMNAME){
SQLiteDatabase db=this.getReadableDatabase();
// Cursor cursor =db.query(TABLE_NAME,null, null,null,null,null,null);
Cursor cursor = db.query(TABLE_NAME, new String[]{ITEMNAME},null,null,null,null,null);
Log.i("DataBase Count","Total Records" + cursor.getCount());
if ( cursor.getCount() >0 )
{
String[] arrData = new String[cursor.getCount()];
int i = 0 ;
while (cursor.moveToNext())
{
arrData[i]=cursor.getString(cursor.getColumnIndex(ITEMNAME)) ;
i++;
}
return arrData;
}
else
{
return new String[] {};
}
}
public int numberOfRows (){
SQLiteDatabase db=this.getReadableDatabase();
int numbrows = (int) DatabaseUtils.queryNumEntries(db,ITEM_TABLE);
return numbrows;
}
public int getLastRow( ){
int id = 0;
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor = db.query(ITEM_TABLE, new String[] {DBHelper.ITEM_CODE},null,null,null,null,null);
if (cursor.moveToLast()) {
id = cursor.getInt(0);
}
cursor.close();
db.close();
return id;
}
public int getLastId(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor =db.rawQuery("Select max(item_code) from " + ITEM_TABLE + "", null );
cursor.moveToLast();
cursor.getInt(0);
return cursor.getInt(0);
}
public boolean update_item_mst(String itemcode, String itemname, String itempack, Integer itempackconv, String barcode, String manfcode,
String catgcode, String contcode, Double itemdisc, int gstperce, String itemrack, String itemshelf,
String timestamp, String itemlbno, Double itemlmrp, Integer itemminlvl, Integer itemmaxlvl, String schedrug,
String hsncode){
SQLiteDatabase db =this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(ITEM_NAME,itemname);
contentValues.put(ITEM_PACK,itempack);
contentValues.put(MANF_CODE,manfcode);
contentValues.put(CATG_CODE,catgcode);
contentValues.put(CONT_CODE,contcode);
contentValues.put(ITEM_DISC,itemdisc);
contentValues.put(GST_PERCE,gstperce);
contentValues.put(ITEM_RACK,itemrack);
contentValues.put(ITEM_SHELF,itemshelf);
contentValues.put(TIME_STAMP,timestamp);
contentValues.put(ITEM_LBNO,itemlbno);
contentValues.put(ITEM_LMRP,itemlmrp);
contentValues.put(ITEM_MINLVL,itemminlvl);
contentValues.put(ITEM_MAXLVL,itemmaxlvl);
db.update(ITEM_TABLE,contentValues," ITEM_CODE " + " = " + itemcode , null );
return true;
}
public void DeleteRecords(String itemcode) {
SQLiteDatabase db =this.getWritableDatabase();
db.delete(ITEM_TABLE,"ITEM_CODE like" + itemcode,null);
}
public boolean CheckDuplicateRecords(String FIELD_NAME) {
SQLiteDatabase db = this.getReadableDatabase();
String str = "select item_name from " + ITEM_TABLE + " where item_name like '" + FIELD_NAME + "'";
Cursor cursor = db.rawQuery(str, null);
if (cursor.getCount() > 0) {
return true;
} else {
return false;
}
}
}
Main Activity :
private void loadFragment(OpeningStockFragment fragment) {
// create a FragmentManager
FragmentManager fm = getSupportFragmentManager();
// create a FragmentTransaction to begin the transaction and replace the Fragment
FragmentTransaction fragmentTransaction = fm.beginTransaction();
// replace the FrameLayout with new Fragment
fragmentTransaction.add(R.id.frameOpeningStock,fragment);
fragmentTransaction.commit(); // save the changes
}
btn_openstock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// FragmentManager fm = getSupportFragmentManager();
// FragmentTransaction fragmentTransaction = fm.beginTransaction();
// fragmentTransaction.add(R.id.frameOpeningStock,new OpeningStockFragment());
// fragmentTransaction.commit(); // save the changes
loadFragment(new OpeningStockFragment());
}
});
mydb is null, therefore you cannot call its methods. You will need to make sure you do one or more of the following, depending on your needs:
initialize it
only execute its methods if it is not null
catch and handle exceptions when it is null

Clear QList that is being used by QSerial

I have the following bit of code:
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updatecommstatus()));
timer -> start();
void MainWindow::updatecommstatus()
{
const auto infos = QSerialPortInfo::availablePorts();
for (const QSerialPortInfo &info : infos) {
QString s = QObject::tr("Port: ") + info.portName() + "\n"
+ QObject::tr("Location: ") + info.systemLocation() + "\n"
+ QObject::tr("Description: ") + info.description() + "\n"
+ QObject::tr("Manufacturer: ") + info.manufacturer() + "\n"
+ QObject::tr("Serial number: ") + info.serialNumber() + "\n"
+ QObject::tr("Vendor Identifier: ") + (info.hasVendorIdentifier() ? QString::number(info.vendorIdentifier(), 16) : QString()) + "\n"
+ QObject::tr("Product Identifier: ") + (info.hasProductIdentifier() ? QString::number(info.productIdentifier(), 16) : QString()) + "\n"
+ QObject::tr("Busy: ") + (info.isBusy() ? QObject::tr("Yes") : QObject::tr("No")) + "\n";
if (QString::number(info.vendorIdentifier(), 16) == "16d0" && QString::number(info.productIdentifier(), 16) == "650")
{
ui->label_commport->setText(info.portName());
}
else
{
ui->label_commport->setText("COM Error");
}
}
}
It is utilising QSerial to display all the available COM ports info. I want to display the portName in a label when certain vendorIdentifierand and productIdentifier match some number.
The above code works well when the device is plugged in (my label displays the right information). But I want to have it when I unplug it that the label displays COM Error. This part does not work. The above code is being targetted by a QTimer and updated, but the Qlist infos is not clearing. Basically, how can I clear this Qlist ? infos.clear(); does not work.
As #lucaAngiolini alluded to in his comment, the scope of you label update seems wrong. I think your trying to do actually compile all available ports into a string, and then set the label thereafter.
void MainWindow::updatecommstatus()
{
const auto infos = QSerialPortInfo::availablePorts();
QStringList comport_labels;
if (infos.empty())
comprt_labels << "COM Error";
for (const QSerialPortInfo &info : infos) {
QString s = QObject::tr("Port: ") + info.portName() + "\n"
+ QObject::tr("Location: ") + info.systemLocation() + "\n"
+ QObject::tr("Description: ") + info.description() + "\n"
+ QObject::tr("Manufacturer: ") + info.manufacturer() + "\n"
+ QObject::tr("Serial number: ") + info.serialNumber() + "\n"
+ QObject::tr("Vendor Identifier: ") + (info.hasVendorIdentifier() ? QString::number(info.vendorIdentifier(), 16) : QString()) + "\n"
+ QObject::tr("Product Identifier: ") + (info.hasProductIdentifier() ? QString::number(info.productIdentifier(), 16) : QString()) + "\n"
+ QObject::tr("Busy: ") + (info.isBusy() ? QObject::tr("Yes") : QObject::tr("No")) + "\n";
if (QString::number(info.vendorIdentifier(), 16) == "16d0" && QString::number(info.productIdentifier(), 16) == "650")
{
comport_labels << info.portName();
}
else
{
comport_labels << "COM Error";
}
}
ui->label_commport->setText(comport_labels.join(","));
}

Try catch trouble in netbeans

I'm trying to create a search engine that gets information from my SQL database. Right now I'm struggling to make the combobox and textfield work. So far I can only make the first part of the code work, it allows the user to search for a name in the database. The rest however doesn't work at all, resulting in just an empty window where the info should pop up.
Here are some translations of the Swedish words present in the code:
Namn - Name
sokt - Searched
ANSTALLD - Employee
Aid - Employee id
telefon - phone
try
{
if(jComboBoxSokAID.getSelectedItem().equals("Namn"))
{
String namn = jTextFieldSokText.getText();
String namnQuery = "select * from ANSTALLD where namn = '" + namn + "'";
try
{
HashMap <String, String> soktNamn = idb.fetchRow(namnQuery);
jTextAreaSpecialistInfo.setText("Namn: " + soktNamn.get("namn") + "\n" + "Aid: " + soktNamn.get ("aid") + "\n" + "Telefon: " + soktNamn.get ("telefon") + "\n" + "Mail: " + soktNamn.get ("mail"));
if(jComboBoxSokAID.getSelectedItem().equals("Mail"))
{
String mail = jTextFieldSokText.getText();
String mailQuery = "select * from ANSTALLD where mail = '" + mail + "'";
try
{
HashMap <String, String> soktMail = idb.fetchRow(mailQuery);
jTextAreaSpecialistInfo.setText("Namn: " + soktMail.get("namn") + "\n" + "Aid: " + soktMail.get ("aid") + "\n" + "Telefon: " + soktMail.get ("telefon") + "\n" + "Mail: " + soktMail.get ("mail"));
if(jComboBoxSokAID.getSelectedItem().equals("Telefon"))
{
String telefon = jTextFieldSokText.getText();
String telefonQuery = "select * from ANSTALLD where telefon = '" + telefon + "'";
try
{
HashMap <String, String> soktTelefon = idb.fetchRow(telefonQuery);
jTextAreaSpecialistInfo.setText("Namn: " + soktTelefon.get("namn") + "\n" + "Aid: " + soktTelefon.get ("aid") + "\n" + "Telefon: " + soktTelefon.get ("telefon") + "\n" + "Mail: " + soktTelefon.get ("mail"));
if(jComboBoxSokAID.getSelectedItem().equals("AID"))
{
String AID = jTextFieldSokText.getText();
String AIDQuery = "select * from ANSTALLD where aid = '" + AID + "'";
try
{
HashMap <String, String> soktAID = idb.fetchRow(AIDQuery);
jTextAreaSpecialistInfo.setText("Namn: " + soktAID.get("namn") + "\n" + "Aid: " + soktAID.get ("aid") + "\n" + "Telefon: " + soktAID.get ("telefon") + "\n" + "Mail: " + soktAID.get ("mail"));
}
catch (InformatikException e)
{
if(jComboBoxSokAID == null)
jTextAreaSpecialistInfo.setText("Sökningen gav inga resultat");
}
}
}
catch (InformatikException e)
{
}
}
}
catch (InformatikException e)
{
}
}
}
catch (InformatikException e)
{
}
Don't write code this way.
Never have empty catch blocks.
I prefer to have a single try/catch in a method. Nesting them this way is an indication that you ought to refactor a method that's doing too much.
You've mingled persistence and UI code together in the worst way possible. Tease them apart so you can test and use them separately.
You don't close any database resources. This will come to grief.

unable to construct a complex structure in c++

I have two base structures like following :
struct stuSectionProperties
{
int Field1; // Row | BoxNo | SplitterNo
int Field2; // Col | Adapter | -
double Latitude;
bool IsEast;
int Band;
int CableNo;
SDP::Global::enuSections::Type Section;
stuSectionProperties()
{
this->Field1 = -1;
this->Field2 = -1;
this->Latitude = -1;
this->Band = -1;
this->Section = SDP::Global::enuSections::None;
this->CableNo = -1;
}
const char* toStr()
{
return ((QString) (QString::number(this->Field1) + " , " + QString::number(this->Field2) + " , " + QString::number(Latitude) + " , " + QString::number(IsEast) + " , " + QString::number(Band) + " , "
+ QString::number((int) Section) + QString::number((int) CableNo))).toStdString().c_str();
}
};
and
struct stuSearchResult
{
stuSectionProperties MyData;
QList<stuSectionProperties> Connections;
stuSearchResult()
{
this->MyData.Field1 = -1;
this->MyData.Field2 = -1;
this->MyData.Latitude = -1;
this->MyData.Band = -1;
this->MyData.Section = SDP::Global::enuSections::None;
this->MyData.CableNo = -1;
stuSectionProperties stuDummy;
stuDummy.Band=-1;
stuDummy.CableNo=-1;
stuDummy.Field1=-1;
stuDummy.Field2=-1;
stuDummy.IsEast=-1;
stuDummy.Latitude=-1;
stuDummy.Section= SDP::Global::enuSections::None;
this->Connections.append(stuDummy);
}
const char * toStr()
{
return ((QString) (QString::number(this->MyData.Field1) + " , " + QString::number(this->MyData.Field2) + " , " + QString::number(this->MyData.Latitude) + " , " + QString::number(this->MyData.IsEast) + " , " + QString::number(this->MyData.Band) + " , "
+ QString::number((int) this->MyData.Section) + QString::number((int) this->MyData.CableNo)) + " , " + QString::number(this->Connections[0].Field1) + " , " + QString::number(this->Connections[0].Field2) ).toStdString().c_str();
}
};
whenever I try to create an instance out of second the structure and then try to call its toStr() member I'll get an erro which is saying that these lines have some issues :
+ QString::number(this->Connections[0].Field1) + " , " + QString::number(this->Connections[0].Field2)
can you please tell me whats my problem exactly?
regards.
the assert error says Connections doesn't have the element you referenced. if you print out Connections.size() how many elements does it say the list contains?
returning string.c_str() could be a potential memory issue, as it's returning a pointer to memory that has been freed.
in c++, custom printing is often done by overloading the stream operator in your class:
friend std::ostream &operator<<(std::ostream &os, const myClass &c)
{
return os << c.some << c.val;
}
...
cout << myObj << endl;
...
strstream ss;
ss << "cool: " << myObj << " " << 55;
string s = ss.str();
you could also just pass a reference to a string object in your toStr function:
makeString(string &s)
{
...
s = qstr.toStdString();
}
string s;
makeString(s);
Yes the code has many issues
Normally people don't write "this->x"; they just write "x"; the "this->" is implicit inside methods
As the other answer pointed out, c_str() points to invalid memory here
However, the Connections list should contain at least one element because the constructor appends it there. I think it would help if the poster would also post the code to allocate the structure. It looks like the constructor doesn't get called OR there is other code that clears the Connections list before toStr() is actually called.