How to populate/create new classes from Strings/html data? JAVA
Suppose I have a bunch of Strings, I need to now create/write new classes from all of the data. For example, let's say I have the formatted String data here with two items that need to be created:
STAMINA
You have an amazing amount of stamina.
PREREQUISITE: Health 13
BENEFIT: You recover vitality points twice as fast as normal. So, if
you would normally recover 1 hp per level per hour,
with this feat you recover 2 hp per level per hour. A
******* character with this feat recovers 4 hp per
level per hour.
CHITINOUS
You have especially thick armor for a member of your species.
PREREQUISITE: Health 13, damage reduction as a species trait
BENEFIT: The damage reduction you receive as a species trait is
increased by 1. This bonus does not apply
to DR imparted by equipment.
SPECIAL: This feat can be selected multiple times. Each time you
select it, its effects stack.
By this time, this has been added to a hashmap, with the Feat title/name as the key and the rest of the data as a String for the value.
What I need to do now is create new class files for each "Feat", Stamina and Chitnous. So after grabbing the Stamina key and its value (everything after Stamina) from the map, the above data would then result in something like below.
First, a Stamina class that extends the abstract Feat class.
public class Stamina extends Feat {
public Stamina() {
super("STAMINA", "You have an amazing amount of stamina.\n" +
" PREREQUISITE: Health 13\n" +
" BENEFIT: You recover hp twice as fast as normal. So,
if you would normally recover 1 hp per level per hour,
with this feat you recover 2 hp per level per hour.
A ******* character with this feat recovers 4 hp points per
level per hour.");
prereqs.put("CON", 13);//This is a method that populates when seeing "PREREQUISITE" in the String
}
}
Notice there is an additional line that calls a helper method in addition to the call to super(String name, String data).
After this, the algorithm should generate another class file Chitnous and put it in the same directory as the new Stamina class file, however it'd be superfluous for me to write out that example.
Thanks in advance!
TL:DR How do I take Strings and from them write new class files to a target directory in my Android project? To be clear I don't need to initialize objects, I'm trying to populate code from Strings. This would happen in a singleton method/only ever happen once.
See also questions close to this topic
-
unable to find valid certification path to requested target (wsimport)
I want to parse WSDL in cmd and when I run the code, it gives me this error: C:\Users\Karamoz\sei>wsimport https://pre.shatelmobile.ir/externalclient/services/inventory/v7.2?wsdl parsing WSDL...
[ERROR] sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Failed to read the WSDL document: https://pre.shatelmobile.ir/externalclient/services/inventory/v7.2?wsdl, because 1) could not find the document; /2) the document could not be read; 3) the root element of the document is not .
[ERROR] Could not find wsdl:service in the provided WSDL(s):
At least one WSDL with at least one service definition needs to be provided.
Failed to parse the WSDL.
How can I fix this??? tnx :)
-
Scala extend trait field not found
I have a scala trait with a public UUID that has a default value:
trait pet { var uuid_ : UUID = UUID.randomUUID }
now I am creating multiple classes, also in scala:
class dog extends pet { var foo = 1 } class cat extends pet { } class fish extends pet { }
After that I created a method in Java (old project with both languages mixed).
Here the snipped with my problem. In the variablesomePet
is an instance ofdog
,cat
orfish
. But it is not clear what of them exactly:// printing all variables in the console for human testing Serializer.printAllFields(somePet); // The somePet Variable must be a pet if(!pet.class.isAssignableFrom(somePet.getClass())) throw new Exception("Not a pet."); // get the UUID of the pet UUID uuid_; try { Field f = pet.class.getField("uuid_"); f.setAccessible(true); uuid_ = (UUID) f.get(somePet); }catch(Exception e){ // no uuid found throw e; }
But when I run the code I get the following error:
Exception in thread "main" java.lang.NoSuchFieldException: uuid_
And the stacktrace points on the line with
Field f = pet.class.getField("uuid_");
.
But what is wrong with the code?
An alternative I thought was replacing this exact line with:Field f = ntObj.getClass().getField("uuid_");
But this also fails.
So where is the variableuuid_
?
Because when I print out all variables in the console of the currentsomePet
with a Serializer, I get something like* cat.uuid_ = 34d7a781-472d-4d98-861e-7cff08045445;
or
* dog.foo = 1 * dog.uuid_ = 34d7a781-472d-4d98-861e-7cff08045445;
in the console.
So the variableuuid_
is there with a default value.
(I am using the serializerSerializer.printAllFields(somePet);
of the java util.)So how do I get the
uuid_
variable in my java snippet? -
Reading characters from files
Just trying to figure out the best method for reading in files, iterating through each character and performing an action on them.
I believe the correct implementation is somewhere between the middle of these two solutions. Using Reader and .readNBytes. I've used US_ASCII in the first example as UTF_8 characters can be more than 1 byte. US_ASCII has a strict 1-to-1 encoding so won't break, unless non-ascii characters show up.
void customCharReader(File file, int n) throws IOException { if(n < 0){ throw new IndexOutOfBoundsException("Value of 'n' is smaller than 0 - nothing to read!"); } byte[] buffer2 = new byte[n]; int pos1; InputStream reader2 = new FileInputStream( file ); pos1 = reader2.readNBytes(buffer2, 0, n); // unlike just 'read', this does guarantee for (int i = 1; i < pos1; i += 2) buffer2[i] = ' '; System.out.println( new String( buffer2, 0, pos1, StandardCharsets.US_ASCII )); /* Implementation using .read() int pos2 = 0; char[] buffer = new char[n]; Reader reader = new InputStreamReader( new FileInputStream(file)); while (pos2 < n) { int r = reader.read(buffer, pos2, n - pos2); if (r == -1) break; pos2 += r; // track how many bytes we've read so far. } for (int i = 1; i < pos2; i += 2) buffer[i] = ' '; System.out.println(String.valueOf(buffer)); */ }
}
-
Send message to specific contact on Viber using Intent on Android App
Is it possible to send message to specific contact without choosing it after the intent send you to the Viber contact list? I want to send it directly.
- Reduce memory and high cpu usage in Android
-
Which one of these methods is efficient way to populate a recyclerview?(WeakReference vs Strong Reference)
I am populating my recyclerview using
SQLite
and this population is done under a new thread using Runnable.Here is the code:
private class BackgroundRunnable internal constructor(context: NotesFrag) : Runnable { private val weakReference = WeakReference(context) override fun run() { val parentClass = weakReference.get() parentClass!!.list!!.clear() parentClass.listItems!!.clear() parentClass.list = parentClass.dbHandler!!.readAllNotes() if(parentClass.list!!.size == 0) return for (noteReader in parentClass.list!!.iterator()) { // val note = UserNotes() //USING STRONG REFERENCE OR val weakReferrerNote: WeakReference<UserNotes> = WeakReference(UserNotes()) val note = weakReferrerNote.get() //USING WEAK REFERENCE? note!!.noteTitle = noteReader.noteTitle note.noteText = noteReader.noteText note.noteID = noteReader.noteID note.noteColor = noteReader.noteColor note.noteEncrypted = noteReader.noteEncrypted note.noteCheckList = noteReader.noteCheckList note.noteDate = noteReader.noteDate note.noteTempDel = noteReader.noteTempDel note.noteArchived = noteReader.noteArchived note.noteReminderID = noteReader.noteReminderID note.noteReminderText = noteReader.noteReminderText parentClass.listItems!!.add(note) } parentClass.activity!!.runOnUiThread(object : Runnable { override fun run() { parentClass.adapter!!.notifyDataSetChanged() parentClass.list!!.clear() parentClass.list = null return } }) } }
As you can see, there are two ways to get objects in for loop(added the comments). I know the difference between a strong reference and a weak reference however I am little confused that if I use a weak reference to generate an object, what if it gets garbage collected during the population? Would it have any effect on the way recyclerview gets populated? Thinking in worst case scenario(imagine a slow user device with low memory), is this the correct way to do it?
The other method is using strong references like
val note = Usernotes()
. This means that it will not be easily garbage collected and memory consumption would increase. Thinking about worst case here as well, imagine a user with 100+ notes, that means 100+ strong objects created hence waste of memory? I am trying to make my app as efficient as possible by trying to think of worst cases and implement an algorithm that could handle maximum numbers of worst cases efficiently. -
Foo has no suitable constructor but program runs
In the following code, all the special functions have been deleted to see whether copy initialization takes place upon
Foo f = funnc();
and it does construction and initializes the
f
, by coping that.But, intelligence keep telling me,
"class Foo has no suitable copy constructor"
at following mentioned two lines.
#include <iostream> class Foo { private: int m_foobar; public: Foo(int value) : m_foobar(value) { std::cout << "Constructing...\n"; } explicit Foo(const Foo& other) = delete; Foo& operator=(const Foo&) = delete; explicit Foo(Foo&& other) = delete; Foo& operator=(Foo&&) = delete; }; Foo funnc() { return Foo(1); } // here: "class Foo has no suitable copy constructor" int main() { Foo f = funnc(); // also here: "class Foo has no suitable copy constructor" return 0; }
- Even though I have deleted the copy/ move constructors, how does the copy initialization happen?
- Is MSVS2017's intelligence is saying it correct and the compiler has any bug?
Edit
As from comments I tried with different compilers:
- In Coliru GCC-std=c++17 -O2 : compiles with warning
- Wandbox clang++ prog.cc -Wall -Wextra -std=c++17 : compiles with warning
- Wandbox g++ prog.cc -Wall -Wextra -std=c++17 : compiles with warning
- But, in godbolt.org -Wall -Wextra -std=c++17 : MSVC failed to compile. But my MSVC 2017 compiler allowed it to compile.
-
Use a class object inside of another class? or just use fields?
I am practicing OOP Inheritance and came across a question, which I have a few ideas on an answer to, but I am not sure what is the "correct" way of thinking.
Say you have a class for a Person. That person has a name. Would you create a class for Name, then make an object of it inside of Person? Or would you just use fields for the first and last name?
Personally, I think that if it doesn't manipulate the data or isn't a lot of data - then I may as well just create 2 fields for first and last name at the class at the top of the inheritance tree so it will be inherited by all the sub classes.
Am I thinking about that correctly?
Thanks :D
Bryan
-
PHP class manipulating
class example{ static function toArray($notFormattedArray){ return ["ID" => $notFormattedArray->ID] } }
I want to manipulate array before toArray method with abstract class or whatever but user mustn't see this function in example class.
Example Order
- example->toArray($notFormattedArray) (Defining) ->
- Manipulating Array from user so $example->toArray() function ->
- Manipulating Array from other method or abstract class ->
- return
-
How to populate a cluster for stress testing using a given schema in Cassandra?
I'm in the current situation : I would like to stress test my Cassandra cluster with different types of schema. For example, I would have a schema designed to stress IO, another one to stress CPU, and several ones for operational usage. I don't have any dataset, or these datasets are difficult to generate.
How could I populate my cluster with data based on these schemas ?
I used cassandra-stress and played with the options, but it seems to be only generating the same data over time and simply replacing previous rows (except for the default schema). The amount of data produced is inferior to the cache size, so whenever I set up a read test with different setup, I get the same results.
-
SQLite column not added/ no such column problem
I wanted to populate the recyclerView in the MainScreen JAVA when I click the fab. But when I click the fab the code that only happens is the
clear()
and I don't know if they are added in the SQLite Database because when I go to the mainscreen the recyclerview is still empty... I dont know what is the meaning of the error and I do not know what is the error in my code. Please see my codes, please help..The error line is these codes in the switch statement:
mDatabase.insert(ItemContract.ItemEntry.TABLE_NAME, null, cv);
What is wrong?
THIS IS THE MAINSCREEN CODE
package com.example.admin.test2; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class MainScreen extends Fragment { private ArrayList <ExampleItem> mExampleList; private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; private ItemAdapter itemAdapter; public MainScreen() { // Required empty public constructor } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_main_screen, container, false); ItemDBHelper dbHelper = new ItemDBHelper(getActivity()); mDatabase = dbHelper.getWritableDatabase(); mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView); mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); itemAdapter = new ItemAdapter(getContext(), getAllItems()); mRecyclerView.setAdapter(itemAdapter); /* mExampleList = new ArrayList <>(); mExampleList.add(new ExampleItem(R.drawable.food, "", "", "ADD EXPENSES")); mRecyclerView = view.findViewById(R.id.recyclerView); mRecyclerView.setHasFixedSize(true); mLayoutManager = new LinearLayoutManager(getContext()); mAdapter = new ExampleAdapter(mExampleList); mRecyclerView.setLayoutManager(mLayoutManager); mRecyclerView.setAdapter(mAdapter); */ return view; } public SQLiteDatabase mDatabase; private Cursor getAllItems() { return mDatabase.query( ItemContract.ItemEntry.TABLE_NAME, null, null, null, null, null, null ); } }
THIS IS THE EXPENSE JAVA CODE
package com.example.admin.test2; import android.app.DatePickerDialog; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.DatePicker; import android.widget.EditText; import android.widget.Spinner; import java.util.ArrayList; import java.util.Calendar; public class Expense extends Fragment { public Expense() { // Required empty public constructor } //SQLite DATABASE public SQLiteDatabase mDatabase; //SPINNER Spinner sp1; CustomAdapter adapter; String[] names = {"Food & Drink", "Shopping", "Transportation", "Home", "Bills & Fees", "Entertainment", "Healthcare", "Education", "Beauty", "Others"}; int[] images = {R.drawable.food, R.drawable.shopping, R.drawable.transportation, R.drawable.home, R.drawable.bills, R.drawable.entertainment, R.drawable.medical, R.drawable.education, R.drawable.beauty, R.drawable.others}; //DATE PICKER private EditText mDisplayDate; private DatePickerDialog.OnDateSetListener mDateSetListener; //FOR THE ADD ITEM FloatingActionButton fab; private ArrayList<ExampleItem> mExampleList; private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; EditText amount; EditText detail; private ItemAdapter itemAdapter; @Nullable @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate (R.layout.fragment_expense, container, false); ItemDBHelper dbHelper = new ItemDBHelper(getActivity()); mDatabase = dbHelper.getWritableDatabase(); //spinner sp1 = (Spinner)view.findViewById(R.id.customSpinner); adapter = new CustomAdapter(getActivity(), names, images); sp1.setAdapter(adapter); //fab onClick - sending values to the recycler view fab = (FloatingActionButton) view.findViewById(R.id.fabs); amount = (EditText) view.findViewById(R.id.textAmountt); detail = (EditText) view.findViewById(R.id.textDetailss); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int pos = sp1.getSelectedItemPosition(); String label; String description = detail.getText().toString(); Double value = Double.parseDouble(amount.getText().toString()); ContentValues cv = new ContentValues(); switch (pos) { case 0: label = "Food & Drink"; cv.put(ItemContract.ItemEntry.COLUMN_LABEL, label); cv.put(ItemContract.ItemEntry.COLUMN_DETAIL, description); cv.put(ItemContract.ItemEntry.COLUMN_AMOUNT, value); mDatabase.insert(ItemContract.ItemEntry.TABLE_NAME, null, cv); amount.getText().clear(); detail.getText().clear(); case 1: label = "Shopping"; cv.put(ItemContract.ItemEntry.COLUMN_LABEL, label); cv.put(ItemContract.ItemEntry.COLUMN_DETAIL, description); cv.put(ItemContract.ItemEntry.COLUMN_AMOUNT, value); mDatabase.insert(ItemContract.ItemEntry.TABLE_NAME, null, cv); amount.getText().clear(); detail.getText().clear(); case 2: label = "Transportation"; cv.put(ItemContract.ItemEntry.COLUMN_LABEL, label); cv.put(ItemContract.ItemEntry.COLUMN_DETAIL, description); cv.put(ItemContract.ItemEntry.COLUMN_AMOUNT, value); mDatabase.insert(ItemContract.ItemEntry.TABLE_NAME, null, cv); amount.getText().clear(); detail.getText().clear(); case 3: label = "Home"; cv.put(ItemContract.ItemEntry.COLUMN_LABEL, label); cv.put(ItemContract.ItemEntry.COLUMN_DETAIL, description); cv.put(ItemContract.ItemEntry.COLUMN_AMOUNT, value); mDatabase.insert(ItemContract.ItemEntry.TABLE_NAME, null, cv); amount.getText().clear(); detail.getText().clear(); case 4: label = "Bills & Fees"; cv.put(ItemContract.ItemEntry.COLUMN_LABEL, label); cv.put(ItemContract.ItemEntry.COLUMN_DETAIL, description); cv.put(ItemContract.ItemEntry.COLUMN_AMOUNT, value); mDatabase.insert(ItemContract.ItemEntry.TABLE_NAME, null, cv); amount.getText().clear(); detail.getText().clear(); case 5: label = "Entertainment"; cv.put(ItemContract.ItemEntry.COLUMN_LABEL, label); cv.put(ItemContract.ItemEntry.COLUMN_DETAIL, description); cv.put(ItemContract.ItemEntry.COLUMN_AMOUNT, value); mDatabase.insert(ItemContract.ItemEntry.TABLE_NAME, null, cv); amount.getText().clear(); detail.getText().clear(); case 6: label = "Healthcare"; cv.put(ItemContract.ItemEntry.COLUMN_LABEL, label); cv.put(ItemContract.ItemEntry.COLUMN_DETAIL, description); cv.put(ItemContract.ItemEntry.COLUMN_AMOUNT, value); mDatabase.insert(ItemContract.ItemEntry.TABLE_NAME, null, cv); amount.getText().clear(); detail.getText().clear(); case 7: label = "Education"; cv.put(ItemContract.ItemEntry.COLUMN_LABEL, label); cv.put(ItemContract.ItemEntry.COLUMN_DETAIL, description); cv.put(ItemContract.ItemEntry.COLUMN_AMOUNT, value); mDatabase.insert(ItemContract.ItemEntry.TABLE_NAME, null, cv); amount.getText().clear(); detail.getText().clear(); case 8: label = "Beauty"; cv.put(ItemContract.ItemEntry.COLUMN_LABEL, label); cv.put(ItemContract.ItemEntry.COLUMN_DETAIL, description); cv.put(ItemContract.ItemEntry.COLUMN_AMOUNT, value); mDatabase.insert(ItemContract.ItemEntry.TABLE_NAME, null, cv); amount.getText().clear(); detail.getText().clear(); case 9: label = "Others"; cv.put(ItemContract.ItemEntry.COLUMN_LABEL, label); cv.put(ItemContract.ItemEntry.COLUMN_DETAIL, description); cv.put(ItemContract.ItemEntry.COLUMN_AMOUNT, value); mDatabase.insert(ItemContract.ItemEntry.TABLE_NAME, null, cv); amount.getText().clear(); detail.getText().clear(); } } }); //int pos = sp1.getSelectedItemPosition(); //date picker mDisplayDate = (EditText) view.findViewById(R.id.datePick); mDisplayDate.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); DatePickerDialog dialog = new DatePickerDialog(getActivity(), mDateSetListener, year, month, day); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.show(); } }); mDateSetListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int day) { //Calendar calendar = Calendar.getInstance(); //String currentDate = DateFormat.getDateInstance().format(calendar.getTime()); month = month + 1; String date = month + "-" + day + "-" + year; mDisplayDate.setText(date); } }; return view; } } }
THIS IS THE ITEMADAPTER
package com.example.admin.test2; import android.content.Context; import android.database.Cursor; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.Switch; import android.widget.TextView; public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemViewHolder> { private Context mContext; private Cursor mCursor; public ItemAdapter(Context context, Cursor cursor) { mContext = context; mCursor = cursor; } public class ItemViewHolder extends RecyclerView.ViewHolder { public ImageView itemImage; public TextView labelText; public TextView detailText; public TextView amountText; public ItemViewHolder(@NonNull View itemView) { super(itemView); itemImage = itemView.findViewById(R.id.imageIcon); labelText = itemView.findViewById(R.id.textLabel); detailText = itemView.findViewById(R.id.textDetails); amountText = itemView.findViewById(R.id.textAmount); } } @NonNull @Override public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { LayoutInflater inflater = LayoutInflater.from(mContext); View view = inflater.inflate(R.layout.customlist, parent, false); return new ItemViewHolder(view); } @Override public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) { if (!mCursor.moveToPosition(position)){ return; } String label = mCursor.getString(mCursor.getColumnIndex(ItemContract.ItemEntry.COLUMN_LABEL)); String detail = mCursor.getString(mCursor.getColumnIndex(ItemContract.ItemEntry.COLUMN_DETAIL)); double amount = mCursor.getDouble(mCursor.getColumnIndex(ItemContract.ItemEntry.COLUMN_AMOUNT)); //holder.itemImage.setImageDrawable(); switch (label){ case "Food & Drink": holder.itemImage.setImageResource(R.drawable.food); case "Shopping": holder.itemImage.setImageResource(R.drawable.shopping); case "Transportation": holder.itemImage.setImageResource(R.drawable.transportation); case "Home": holder.itemImage.setImageResource(R.drawable.home); case "Bills & Fees": holder.itemImage.setImageResource(R.drawable.bills); case "Entertainment": holder.itemImage.setImageResource(R.drawable.entertainment); case "Healthcare": holder.itemImage.setImageResource(R.drawable.medical); case "Education": holder.itemImage.setImageResource(R.drawable.education); case "Beauty": holder.itemImage.setImageResource(R.drawable.beauty); case "Others": holder.itemImage.setImageResource(R.drawable.others); } holder.labelText.setText(label); holder.detailText.setText(detail); holder.amountText.setText(String.valueOf(amount)); } @Override public int getItemCount() { return mCursor.getCount(); } public void swapCursor (Cursor newCursor){ if(mCursor != null){ mCursor.close(); } mCursor = newCursor; if (newCursor != null){ notifyDataSetChanged(); } } }
ITEMDBHELPER CODE
package com.example.admin.test2; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.example.admin.test2.ItemContract.*; public class ItemDBHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "itemlist.db"; public static final int DATABASE_VERSION = 1; public ItemDBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { final String SQL_CREATE_ITEMLIST_TABLE = "CREATE TABLE " + ItemEntry.TABLE_NAME + " (" + ItemEntry.COLUMN_LABEL + " TEXT NOT NULL, " + ItemEntry.COLUMN_DETAIL + " TEXT, " + ItemEntry.COLUMN_AMOUNT + "DOUBLE NOT NULL" + ");"; db.execSQL(SQL_CREATE_ITEMLIST_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + ItemEntry.TABLE_NAME); onCreate(db); } }
THE ITEMCONTRACT CODE
package com.example.admin.test2; import android.provider.BaseColumns; public class ItemContract { private ItemContract() {} public static final class ItemEntry implements BaseColumns { public static final String TABLE_NAME = "itemList"; public static final String COLUMN_LABEL = "label"; public static final String COLUMN_AMOUNT = "amount"; public static final String COLUMN_DETAIL = "detail"; } }
it has this error
E/SQLiteLog: (1) table itemList has no column named amount E/SQLiteDatabase: Error inserting amount=500.0 label=Food & Drink detail=jsjdjdj android.database.sqlite.SQLiteException: table itemList has no column named amount (code 1): , while compiling: INSERT INTO itemList(amount,label,detail) VALUES (?,?,?) ################################################################# Error Code : 1 (SQLITE_ERROR) Caused By : SQL(query) error or missing database. (table itemList has no column named amount (code 1): , while compiling: INSERT INTO itemList(amount,label,detail) VALUES (?,?,?)) ################################################################# at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1096) at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:661) at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588) at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59) at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31) at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1902) at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1771) at com.example.admin.test2.Expense$1.onClick(Expense.java:94) at android.view.View.performClick(View.java:6897) at android.view.View$PerformClick.run(View.java:26101) at android.os.Handler.handleCallback(Handler.java:789) at android.os.Handler.dispatchMessage(Handler.java:98) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6944) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374).... this continues
-
Populate dataGridView with a list inside a dictionary?
I have a dictionary like this:
Dictionary<string, List<string>>
After adding keys and values like this:
resultDic.Add(s, new List<string>()); foreach (DataRow row in schemaTable.Rows) { resultDic[s].Add(row[3].ToString()); }
I then want to display both the string values and the individual values inside the list from the dictionary. To Achieve this, I tried doing like so:
dataGridView2.DataSource = Controller.GetMetaDataTables2().Select(x => new { ColumnName = x.Key, Table = x.Value[0] }).ToList(); dataGridView2.Show();
GetMetaDataTables2 returns a Dictionary like the one above. The problem is that index [0] obviously only gives me the first value, when I want to show the entire list. I want to iterate, but I don't know how to do that here. I'm just starting to understand the LINQ expression. Any ideas?
Grateful for any and all help!