I am implementing an Adapter to take List and Hashmap and turn them into headers and children respectively for an Expandable ListView. In the constructor's Log statements it is showing that the values are being transferred to the local list successfully. But then it suddenly turns null.
I can't pinpoint what went wrong and where. Please help.
Here is my code for the Adapter class:
class ExpandableListViewAdapterDemo extends BaseExpandableListAdapter{
Context context = null;
private List<String> headersList;//semester's name and year
private HashMap<String, List<String>> tableList;//course names with its grades and gpa
static final String TAG = "**Adapter Demo**";
ExpandableListViewAdapterDemo(Context context, List<String> list,
HashMap<String, List<String>> hashMap){
this.context = context;
headersList = list;
tableList = hashMap;
Log.e(TAG, "hashmap list value = "+hashMap.get("Spring 2016"));
Log.e(TAG, "initial table list value = "+tableList.get("Spring 2016"));
printMap(tableList);
//printAll();
Log.e(TAG, "groupCount = "+getGroupCount());
}
void printAll(){
Log.e(TAG, "headers count = "+headersList.size());
for (int i = 0; i < headersList.size() ; i++) {
Log.e(TAG, "header at i="+i+" ,"+headersList.get(i));
}
printMap(tableList);
}
private static void printMap(HashMap mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
HashMap.Entry pair = (HashMap.Entry)it.next();
Log.e(TAG, "#253 : "+pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
#Override
public int getGroupCount() {
Log.e(TAG, "#299 : table list value = "+tableList.get("Spring 2016"));
return headersList.size();
}
#Override
public int getChildrenCount(int i) {
//Log.e(TAG, "at i="+i+" "+headersList.get(i));
int returns = 0;
Log.e(TAG, "#307 : table list value = "+tableList.get("Spring 2016"));
if (tableList.get(headersList.get(i)) != null)
returns = tableList.get(headersList.get(i)).size();
else
Log.e(TAG, "tableList is null");
Log.e(TAG, "details size = "+returns);
Log.e(TAG, "group count = "+getGroupCount());
int tosubtract = 2 * getGroupCount();
if (returns>tosubtract)
returns = returns - tosubtract - 2;
Log.e(TAG, "child count returns = "+String.valueOf(returns) );
return i;
}
#Override
public Object getGroup(int i) {
Log.e(TAG, "#323 : table list value = "+tableList.get("Spring 2016"));
return headersList.get(i);
}
#Override
public Object getChild(int i, int i1) {
Log.e(TAG, "#329 : table list value = "+tableList.get("Spring 2016"));
return tableList.get(headersList.get(i)).get(i1);
}
#Override
public long getGroupId(int i) {
Log.e(TAG, "#335 : table list value = "+tableList.get("Spring 2016"));
return i;
}
#Override
public long getChildId(int i, int i1) {
Log.e(TAG, "#340 : table list value = "+tableList.get("Spring 2016"));
return i1;
}
#Override
public boolean hasStableIds() {
Log.e(TAG, "#347 : table list value = "+tableList.get("Spring 2016"));
return false;
}
#Override
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
Log.e(TAG, "#353 : table list value = "+tableList.get("Spring 2016"));
String semesterTitle = (String) getGroup(i);
if (view == null){
LayoutInflater inf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inf.inflate(R.layout.previous_semesters_result_list_headers, null);
}
TextView semesterName = (TextView) view.findViewById(R.id.semester_name);
semesterName.setText(semesterTitle);
return view;
}
#Override
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
Log.e(TAG, "#367 : table list value = "+tableList.get("Spring 2016"));
String courseIdTitle = (String) getChild(i, i1);
String gpa = (String) getChild(i, i1+getChildrenCount(i));//previously i1+4
String grade = (String) getChild(i, i1+getChildrenCount(i)+getChildrenCount(i));
if (view == null){
LayoutInflater inf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inf.inflate(R.layout.previous_semesters_results_list_child, null);
}
TextView courseIdValue = (TextView) view.findViewById(R.id.course_id_column_value);
courseIdValue.setText(courseIdTitle);
TextView gradeValue = (TextView) view.findViewById(R.id.grade_column_value);
gradeValue.setText(grade);
TextView gpaValue = (TextView) view.findViewById(R.id.gpa_column_value);
gpaValue.setText(gpa);
return view;
}
#Override
public boolean isChildSelectable(int i, int i1) {
Log.e(TAG, "#386 : table list value = "+tableList.get("Spring 2016"));
return true;
}
}
Here is my Log :
You removed the item while printing the map,
it.remove(); // avoids a ConcurrentModificationException
Just remove this it will work fine.
private static void printMap(HashMap mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
HashMap.Entry pair = (HashMap.Entry)it.next();
Log.e(TAG, "#253 : "+pair.getKey() + " = " + pair.getValue());
//it.remove(); // avoids a ConcurrentModificationException
}
}
In your method printMap(), the last statement in the while block is
it.remove(); // avoids a ConcurrentModificationException
This statement may not cause an Exception but it removes the current entry from the HashMap. So after executing
printMap(tableList);
in the Constructor of ExpandableListViewAdapterDemo, the tableList will be empty.
Related
I created an app that has an autoCompleteTextView in order to allow the user to perform search queries.
Once they start typing, a dropdown appears and offers the results.
Now, I would like to make the first item to be fixed and unscrollable which will say something like: can't find? add manually.
How can I make the first item in the suggested dropdown list to be fixed and appear always?
My code for the adapter is:
public class AutoCompleteImageAdapter extends ArrayAdapter<String> implements Filterable {
private ArrayList<String> fullList;
private ArrayList<String> mOriginalValues;
private ArrayFilter mFilter;
private Boolean noResults;
private TextView tv_name;
private ImageView im_cover;
private List<String> url, id;
private StorageReference storageRef;
private FirebaseFirestore db;
public AutoCompleteImageAdapter(Context context, int resource, int textViewResourceId, List<String> objects, List<String> url, List<String> id, Boolean noResult) {
super( context, resource, textViewResourceId, objects );
fullList = (ArrayList<String>) objects;
mOriginalValues = new ArrayList<String>( fullList );
noResults = noResult;
this.url = url;
this.id = id;
}
#Override
public int getCount() {
if (fullList.size() > 40) {
return 40;
} else {
return fullList.size();
}
}
#Override
public String getItem(int position) {
return fullList.get( position );
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
db = FirebaseFirestore.getInstance();
storageRef = FirebaseStorage.getInstance().getReference();
View row = convertView;
String id = this.id.get( position );
LayoutInflater inflater = LayoutInflater.from( getContext() );
if (row == null) {
row = inflater.inflate( R.layout.item_auto_add, parent, false );
}
tv_name = (TextView) row.findViewById( R.id.item_drop );
tv_name.setText( fullList.get( position ) );
im_cover = row.findViewById( R.id.iv_itemCover );
String Url = url.get( position );
if (id.length() > AppConstants.UPLOADED_item_LENGTH) {
storageRef.child( "/itemCovers/" + Url + "/" + Url + ".jpg" ).getDownloadUrl().addOnSuccessListener( new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.with( parent.getContext() ).load( uri ).resize( 110, 160 ).into( im_cover );
}
} ).addOnFailureListener( new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.d( "ERROR", exception + "" );
}
} );
} else {
Picasso.with( parent.getContext() ).load( Uri.parse( Url ) ).error( R.drawable.ic_nocover ).resize( 110, 160 ).into( im_cover );
}
return row;
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ArrayFilter();
}
return mFilter;
}
private class ArrayFilter extends Filter {
private Object lock;
#Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (mOriginalValues == null) {
synchronized (lock) {
mOriginalValues = new ArrayList<String>( fullList );
}
}
if (prefix == null || prefix.length() == 0) {
synchronized (lock) {
ArrayList<String> list = new ArrayList<String>( mOriginalValues );
results.values = list;
results.count = list.size();
}
} else {
final String prefixString = prefix.toString().toLowerCase();
ArrayList<String> values = mOriginalValues;
int count = values.size();
ArrayList<String> newValues = new ArrayList<String>( count );
for (int i = 0; i < count; i++) {
String item = values.get( i );
if (item.toLowerCase().contains( prefixString )) {
newValues.add( item );
}
}
results.values = newValues;
results.count = newValues.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.values != null) {
fullList = (ArrayList<String>) results.values;
} else {
fullList = new ArrayList<String>();
}
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
public void clear() {
if (fullList != null) {
fullList.clear();
notifyDataSetChanged();
}
}
}
Thank you
add it as the first item to your List objects before you pass it to the adapter and then populate the list with data you wanna show as search result so that element 0 is always "can't find? add manually". This way it is always there and the other items change.
and then in the item click listener you can check for the item text and act accordingly if it matches "can't find? add manually".
I think the code below solves your requirement to some level. Do try and comment.
<AutoCompleteTextView
android:layout_below="#+id/edit_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/project"
android:id="#+id/edit_project"
android:completionThreshold="0"
android:completionHint="#string/message"
android:inputType="text"
/>
This code gives a hint at the bottom of the list to the user.
I want to fill an ExpandableListView with a custom Adapter. What I found online is having only one child(one TextView) as a child. In my case, I want to make it have multiple child and data filled after a Background task.
Please help me find what I've done wrong or what should I do as the error as I keep on getting
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.HashMap.put(java.lang.Object, java.lang.Object)' on a null object reference
at com.infy.texpetrol.Activity.CreditReportActivity$GetData.onPostExecute
CreditReportActivity
public class CreditReportActivity extends AppCompatActivity {
private static final String TAG = "CreditBillActivity";
private ConnectionClass connectionClass;
private ProgressDialog progressDialog;
private List<String> cListPetrol, cListDIESEL, cListSPEED, cListOIL;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_credit_report);
String empCode = getIntent().getStringExtra("empCode");
String shift = getIntent().getStringExtra("shift");
String date = getIntent().getStringExtra("date");
connectionClass = new ConnectionClass();
expListView = findViewById(R.id.lvExpandable);
GetData getData = new GetData();
getData.execute(empCode);
}
#SuppressLint("StaticFieldLeak")
private class GetData extends AsyncTask {
boolean bPetrolRS = false;
boolean bDesiRS = false;
boolean bSpedRS = false;
boolean bOilRS = false;
#Override
protected Object doInBackground(Object[] objects) {
String empCode = objects[0].toString();
try {
Connection con = connectionClass.CONN();
String queryPetrol, queryDIESEL, queryOIL, querySPEED;
queryDIESEL = "Some SQL QUERY";
queryPetrol = "Some SQL QUERY";
queryOIL = "Some SQL QUERY";
querySPEED = "Some SQL QUERY";
if (con != null) {
Statement statement1 = con.createStatement();
Statement statement2 = con.createStatement();
Statement statement3 = con.createStatement();
Statement statement4 = con.createStatement();
ResultSet rsPetrol = statement1.executeQuery(queryPetrol);
ResultSet rsDIESEL = statement2.executeQuery(queryDIESEL);
ResultSet rsOIL = statement3.executeQuery(queryOIL);
ResultSet rsSPEED = statement4.executeQuery(querySPEED);
listDataHeader = new ArrayList<>();
cListPetrol = new ArrayList<>();
cListDIESEL = new ArrayList<>();
cListSPEED = new ArrayList<>();
cListOIL = new ArrayList<>();
Log.d(TAG, "doInBackground: rsPetrol " + rsPetrol.next());
if (rsPetrol.next()) {
while (rsPetrol.next()) {
bPetrolRS = true;
cListPetrol.add(rsPetrol.getString("PartyName")
+ "#.#" + rsPetrol.getString("QTY")
+ "#.#" + rsPetrol.getString("Amount"));
}
} else {
bPetrolRS = false;
cListPetrol.add("NONE");
}
Log.d(TAG, "doInBackground: rsDIESEL " + rsDIESEL.next());
if (rsDIESEL.next()) {
while (rsDIESEL.next()) {
bDesiRS = true;
cListDIESEL.add(rsDIESEL.getString("PartyName")
+ "#.#" + rsDIESEL.getString("QTY")
+ "#.#" + rsDIESEL.getString("Amount"));
}
} else {
bDesiRS = false;
cListDIESEL.add("NONE");
}
Log.d(TAG, "doInBackground: rsSPEED " + rsSPEED.next());
if (rsSPEED.next()) {
while (rsSPEED.next()) {
bSpedRS = true;
cListSPEED.add(rsSPEED.getString("PartyName")
+ "#.#" + rsSPEED.getString("QTY")
+ "#.#" + rsSPEED.getString("Amount"));
}
} else {
bSpedRS = false;
cListSPEED.add("NONE");
}
Log.d(TAG, "doInBackground: rsOIL " + rsOIL.next());
if (rsOIL.next()) {
while (rsOIL.next()) {
bOilRS = true;
cListOIL.add(rsOIL.getString("PartyName")
+ "#.#" + rsOIL.getString("QTY")
+ "#.#" + rsOIL.getString("Amount"));
}
} else {
bSpedRS = false;
cListOIL.add("NONE");
}
} else {
Log.d(TAG, "doInBackground: Error in Connection");
}
} catch (Exception e) {
bPetrolRS = false;
Log.d(TAG, "doInBackground: CATCH " + e.getMessage());
}
return empCode;
}
#Override
protected void onPostExecute(Object o) {
progressDialog.hide();
if (!o.toString().isEmpty()) {
listDataHeader.add("DIESEL");
listDataHeader.add("PETROL");
listDataHeader.add("SPEED");
listDataHeader.add("OIL");
if (bDesiRS) {
Log.d(TAG, "onPostExecute: cListDIESEL " + cListDIESEL.size() + " listDataHeader.get(0) " + listDataHeader.get(0));
listDataChild.put(listDataHeader.get(0), cListDIESEL);
} else {
Toast.makeText(CreditReportActivity.this, "NO DATA IN DIESEL", Toast.LENGTH_SHORT).show();
}
if (bPetrolRS) {
Log.d(TAG, "onPostExecute: cListPetrol " + cListPetrol.size() + " listDataHeader.get(1) " + listDataHeader.get(1));
listDataChild.put(listDataHeader.get(1), cListPetrol); //error gets me here
} else {
Toast.makeText(CreditReportActivity.this, "NO DATA IN PETROL", Toast.LENGTH_SHORT).show();
}
if (bOilRS) {
listDataChild.put(listDataHeader.get(2), cListSPEED);
Log.d(TAG, "onPostExecute: cListSPEED " + cListSPEED.size());
} else {
Toast.makeText(CreditReportActivity.this, "NO DATA IN SPEED", Toast.LENGTH_SHORT).show();
}
if (bSpedRS) {
listDataChild.put(listDataHeader.get(3), cListOIL);
Log.d(TAG, "onPostExecute: cListOIL " + cListOIL.size());
} else {
Toast.makeText(CreditReportActivity.this, "NO DATA IN OIL", Toast.LENGTH_SHORT).show();
}
listAdapter = new ExpandableListAdapter(CreditReportActivity.this, listDataHeader, listDataChild);
expListView.setAdapter(listAdapter);
} else {
Toast.makeText(CreditReportActivity.this, "No Data", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(CreditReportActivity.this);
progressDialog.setMessage("Getting your Report");
progressDialog.show();
}
}
}
ExpandableListAdapter
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
private String[] split;
public ExpandableListAdapter(Context _context, List<String> _listDataHeader, HashMap<String, List<String>> _listDataChild) {
this._context = _context;
this._listDataHeader = _listDataHeader;
this._listDataChild = _listDataChild;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return Objects.requireNonNull(this._listDataChild.get(this._listDataHeader.get(groupPosition))).get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#SuppressLint("InflateParams")
#Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
stringSplit(childText);
if (convertView == null) {
LayoutInflater Inflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = Inflater.inflate(R.layout.child, null);
}
TextView txtPartyName = convertView.findViewById(R.id.txt_C_partyName);
txtPartyName.setText(split[0]);
TextView product = convertView.findViewById(R.id.txt_C_COUNT);
product.setText(String.valueOf(childPosition));
TextView qty = convertView.findViewById(R.id.txt_C_qty);
qty.setText(split[1]);
TextView amt = convertView.findViewById(R.id.txt_C_amt);
amt.setText(split[2]);
return convertView;
}
private void stringSplit(String childText) {
split = childText.split("#.#");
}
#Override
public int getChildrenCount(int groupPosition) {
return Objects.requireNonNull(this._listDataChild.get(this._listDataHeader.get(groupPosition)))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#SuppressLint("InflateParams")
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.header, null);
}
TextView lblListHeader = convertView.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
}
You forgot to initialize listDataChild
HashMap<String, List<String>> listDataChild = new HashMap<>();
I implemented the displaying contacts with checkboxes. When I selected the multiple contacts and click the button it shows this error "
Attempt to invoke virtual method 'boolean
java.lang.Boolean.booleanValue()' on a null object reference"
. at mCustomAdapter.mCheckedStates.get(i). So i wrote like this in adapter class is "
mCheckedStates = new LongSparseArray<>(ContactList.size())
And again it shows the same error after assigning some value. When I print the size of the mCustomAdapter.mCheckedStates.size it show the correct value of how many contacts I selected but when getting the value it shows the error. How to solve that?
This is My adapter class :
public class Splitadapter extends BaseAdapter implements Filterable,CompoundButton.OnCheckedChangeListener
{
// public SparseBooleanArray mCheckStates;
LongSparseArray<Boolean> mCheckedStates = new LongSparseArray<>();
private ArrayList<COntactsModel> ContactList;
private Context mContext;
private LayoutInflater inflater;
private ValueFilter valueFilter;
ArrayList<COntactsModel> ContactListCopy ;
public Splitadapter(Context context, ArrayList<COntactsModel> ContactList) {
super();
mContext = context;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.ContactList = ContactList;
this.ContactListCopy = this.ContactList;
mCheckedStates = new LongSparseArray<>(ContactList.size());
System.out.println("asdfghjk" + mCheckedStates);
getFilter();
}//End of CustomAdapter constructor
#Override
public int getCount() {
return ContactListCopy.size();
}
#Override
public Object getItem(int position) {
return ContactListCopy.get(position).getName();
}
#Override
public long getItemId(int position) {
return ContactListCopy.get(position).getId();
}
public class ViewHolder {
TextView textviewName;
TextView textviewNumber;
CheckBox checkbox;
Button b;
int id;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
final int pos = position;
//
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.list, null);
holder.textviewName = (TextView) convertView.findViewById(R.id.name);
holder.textviewNumber = (TextView) convertView.findViewById(R.id.mobile);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.check);
holder.b = convertView.findViewById(R.id.round_icon);
convertView.setTag(holder);
}//End of if condition
else {
holder = (ViewHolder) convertView.getTag();
}//End of else
COntactsModel c = ContactListCopy.get(position);
holder.textviewName.setText(c.getName());
holder.textviewNumber.setText(c.getPhonenum());
holder.checkbox.setTag(c.getId());
holder.checkbox.setChecked(mCheckedStates.get(c.getId(), false));
holder.checkbox.setOnCheckedChangeListener(this);
holder.b.setText(c.getName().substring(0,1));
//holder.id = position;
return convertView;
// }//End of getView method
}
boolean isChecked(long id) {// it returns the checked contacts
return mCheckedStates.get(id, false);
}
void setChecked(long id, boolean isChecked) { //set checkbox postions if it sis checked
mCheckedStates.put(id, isChecked);
System.out.println("hello...........");
notifyDataSetChanged();
}
void toggle(long id) {
setChecked(id, !isChecked(id));
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mCheckedStates.put((Long) buttonView.getTag(), true);
} else {
mCheckedStates.delete((Long) buttonView.getTag());
}
}
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
//Invoked in a worker thread to filter the data according to the constraint.
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<COntactsModel> filterList = new ArrayList<COntactsModel>();
for (int i = 0; i < ContactList.size(); i++) {
COntactsModel ca = ContactList.get(i);
if ((ca.getName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
//COntactsModel contacts = new COntactsModel();
filterList.add(ca);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = ContactList.size();
results.values = ContactList;
}
return results;
}
//Invoked in the UI thread to publish the filtering results in the user interface.
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
ContactListCopy = (ArrayList<COntactsModel>) results.values;
notifyDataSetChanged();
}
}
}
This my Main Activity :
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
public static String TAG = "amount";
ListView mainListView;
ProgressDialog pd;
public static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
final static List<String> name1 = new ArrayList<>();
List<String> phno1 = new ArrayList<>();
List<Long> bal = new ArrayList<>();
List<Bitmap> img = new ArrayList<>();
private Splitadapter mCustomAdapter;
private ArrayList<COntactsModel> _Contacts = new ArrayList<COntactsModel>();
HashSet<String> names = new HashSet<>();
Set<String>phonenumbers = new HashSet<>();
Button select;
int amount=100;
float result;
String ph;
String phoneNumber;
EditText search;
String contactID;
String name;
// private FirebaseAuth mAuth;
// FirebaseUser firebaseUser;
//
// FirebaseFirestore db = FirebaseFirestore.getInstance();
#SuppressLint("StaticFieldLeak")
#Override
protected void onCreate(Bundle savedInstanceState) {
setTitle("Split");
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = findViewById(R.id.search_bar);
final List<String> phonenumber = new ArrayList<>();
System.out.print(phonenumber);
mainListView = findViewById(R.id.listview);
showContacts();
select = findViewById(R.id.button1);
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user chan ged the Text
mCustomAdapter.getFilter().filter(cs.toString());
//
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
//ma.filter(text);
}
});
select.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
StringBuilder checkedcontacts = new StringBuilder();
ArrayList checkedcontacts1 = new ArrayList();
ArrayList names = new ArrayList();
System.out.println(".............." + (mCustomAdapter.mCheckedStates.size()));
System.out.println("name size is" + name1.size());
int a = mCustomAdapter.mCheckedStates.size();
result = ((float) amount / a);
System.out.println("final1 amount is " + result);
long result1 = (long) result;
System.out.println("final amount is " + result1);
for (int k = 0; k < a; k++) {
bal.add(result1);
}
System.out.println("balance" + bal);
System.out.println("selected contacts split amount" + result);
System.out.println("names" + name1.size());
// int as = name1.size();
// mCustomAdapter.mCheckedStates = new LongSparseArray<>(as);
System.out.println("cjgygytygh" + mCustomAdapter.mCheckedStates);
for (int i = 0; i < name1.size(); i++) // it displays selected contacts with amount
{
System.out.println("checked contcts" + mCustomAdapter.mCheckedStates.get(i));
if (mCustomAdapter.mCheckedStates.get(i)) {
checkedcontacts.append(phno1.get(i)).append("\t").append("\t").append("\t").append(result1);
checkedcontacts1.add((phno1.get(i)));
names.add((name1.get(i)));
checkedcontacts.append("\n");
System.out.println("checked contacts:" + "\t" + phno1.get(i) + "\t" + "amount" + "\t" + result1);
}
}
System.out.println("checked names" + names);
System.out.println(
"checkec contcts foggfgfgfgfgf" + checkedcontacts1
);
List<Object> list = new ArrayList<>();
for (Object i : checkedcontacts1) {
list.add(i);
}
System.out.println("checked contacts size is" + checkedcontacts1.size());
HashMap<String, HashMap<String, Object>> Invites = new HashMap<>();
for (int i = 0; i < checkedcontacts1.size(); i++) {
HashMap<String, Object> entry = new HashMap<>();
entry.put("PhoneNumber", list.get(i));
entry.put("Name", names.get(i));
System.out.println("entry is" + entry);
for (int j = i; j <= i; j++) {
System.out.println("phonenumber" + i + ":" + list.get(i));
System.out.println("amount" + j + ":" + bal.get(j));
//dataToSave.put("phonenumber" +i, list.get(i));
entry.put("Amount", bal.get(j));
}
Invites.put("Invite" + i, entry);
}
Intent intent = new Intent(MainActivity.this, Display.class);
intent.putExtra("selected", checkedcontacts1.toString().split(","));
startActivity(intent);
}
});
}
private void showContacts() // it is for to check the build versions of android . if build version is >23 or above it is set the permissions at the run time . if the build version is less than 23 the we give the permissions at manifest file .
{if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
}
else {
mCustomAdapter = new Splitadapter(MainActivity.this,_Contacts);
//ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,aa);
mainListView.setAdapter(mCustomAdapter);
mainListView.setOnItemClickListener(this);
mainListView.setItemsCanFocus(false);
mainListView.setTextFilterEnabled(true);
getAllContacts();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, // it is display the request access permission dilogue box to access the contacts of user.
#NonNull int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission is granted
showContacts();
} else {
Toast.makeText(this, "Until you grant the permission, we canot display the names", Toast.LENGTH_SHORT).show();
}
}
}
private void getAllContacts() {
// it displays the contact phonenumber and name rom the phone book. and add to the list.
ContentResolver cr = getContentResolver();
String[] PROJECTION = new String[] {
ContactsContract.RawContacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.PHOTO_URI,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,
ContactsContract.CommonDataKinds.Photo.CONTACT_ID };
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String filter = ""+ ContactsContract.Contacts.HAS_PHONE_NUMBER + " > 0 and " + ContactsContract.CommonDataKinds.Phone.TYPE +"=" + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
String order = ContactsContract.Contacts.DISPLAY_NAME + " ASC";
Cursor phones = cr.query(uri, PROJECTION, filter, null, order);
while (phones.moveToNext()) {
long id = phones.getLong(phones.getColumnIndex(ContactsContract.Data._ID));
name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
_Contacts.add(new COntactsModel(id,name,phoneNumber));
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
Uri uri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(cr, uri);
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
mCustomAdapter.toggle(arg3);
}
This my Model Class :
public class COntactsModel
{
String phonenum;
long id;
String cname;
boolean selected = false;
public COntactsModel(long id, String name,String phonenumber) {
this.id = id;
this.cname = name;
this.phonenum = phonenumber;
}
public long getId() {
return this.id;
}
public String getName() {
return this.cname;
}
public String getPhonenum() {
return this.phonenum;
}
}
How to solve that error?
I have an ArrayList<Model> type and having fields id,name,isSelected and I have one HashMap which can store only selected items means if the item is clicked it will be stored in HashMap<Intere,Model>, Integer will be id , Model is that object which can be selected. I want to update Arraylist item field isSeleted to true which is present in hashmap. How can i do? I have tried many condition but nothing is working fine.
ArrayList<MainInterestModel> mainInterestList;
public static HashMap<Integer, MainInterestModel> mainIntrestHash = new HashMap<>();
Iterator myVeryOwnIterator = mainIntrestHash.keySet().iterator();
while (myVeryOwnIterator.hasNext()) {
int key = (int) myVeryOwnIterator.next();
MainInterestModel value = (MainInterestModel) mainIntrestHash.get(key);
int id = value.getId();
for (int i = 0; i < mainInterestList.size(); i++) {
MainInterestModel model = mainInterestList.get(i);
if (model.getId() == id) {
model.setSelected(true);
mainInterestList.set(i, model);
} else {
model.setSelected(false);
mainInterestList.set(i, model);
}
}
}
By Default isSelected is false but when the user will click that item will be stored in HashMap later i want to update selection so user interface will show selected items. HashMap has selected items and arraylist have all items but isSelected are false. at the time of showing selected items, I'm taking isSelected is true or not, which working fine, but arraylist update is not working.
My adapter class code
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
final MainInterestModel mainInterestModel = mainInterestModels.get(position);
holder.tvName.setText(mainInterestModel.getName());
holder.ivMainInterest.setImageResource(mainInterestModel.getImage());
// here isSelected is always false because in activity infalting adpter with arraylist, i want to setSeletced by hash object
boolean isSelected = mainInterestModel.isSelected();
if (isSelected) {
holder.ivMainInterest.setImageResource(R.drawable.bath_selector);
Log.e("Is Item selected ::", "" + mainInterestModel.getId());
} else {
holder.ivMainInterest.setImageResource(R.drawable.ic_bath);
Log.e("Is Item deselected ::", "" + mainInterestModel.getId());
}
holder.ivMainInterest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean selection = mainInterestModel.isSelected();
if (selection) {
holder.ivMainInterest.setImageResource(R.drawable.ic_bath);
mainInterestModel.setSelected(false);
mainIntrestHash.remove(mainInterestModel.getId());
Log.e("After Remove SIZE:---", "" + mainIntrestHash.size());
} else {
mainInterestModel.setSelected(true);
holder.ivMainInterest.setImageResource(R.drawable.bath_selector);
mainIntrestHash.put(mainInterestModel.getId(), mainInterestModel);
Log.e("After Adding SIZE:---", "" + mainIntrestHash.size());
}
}
});
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.ivMainInterest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean selection = mainInterestModel.isSelected();
if (selection) {
holder.ivMainInterest.setImageResource(R.drawable.ic_bath);
mainInterestModel.setSelected(false);
} else {
mainInterestModel.setSelected(true);
holder.ivMainInterest.setImageResource(R.drawable.bath_selector);
}
notifyDataSetChanged();
}
});
}
remove hashmap and try to use this.
use this
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class ModelIterator {
public static void main(String arg[]) {
ArrayList<mainModel> mainmoldelList = new ArrayList<mainModel>();
for (int i = 1; i <= 3; i++) {
mainModel m = new mainModel();
m.setId(i);
m.setName("Rajendra" + i);
m.setSelected(false);
mainmoldelList.add(m);
}
mainModel m = new mainModel();
m.setId(0);
m.setName("Rajendra0");
m.setSelected(false);
HashMap<Integer, mainModel> mMap = new HashMap<Integer, mainModel>();
mMap.put(1, m);
Iterator<Entry<Integer, mainModel>> ite = mMap.entrySet().iterator();
while (ite.hasNext()) {
Map.Entry<Integer, mainModel> pair = (Map.Entry<Integer, mainModel>) ite
.next();
int key = pair.getKey();
mainModel mObj = (mainModel) mMap.get(key);
for (int i = 0; i < mainmoldelList.size(); i++) {
if (mainmoldelList.get(i).id == key) {
mainModel tmp = new mainModel();
tmp.setId(mainmoldelList.get(i).id);
tmp.setName(mainmoldelList.get(i).name);
tmp.setSelected(true);
mainmoldelList.add(tmp);
mainmoldelList.remove(i);
}
}
}
for (int i = 0; i < mainmoldelList.size(); i++) {
System.out.println(mainmoldelList.get(i).id + " "
+ mainmoldelList.get(i).name + " "
+ mainmoldelList.get(i).isSelected);
}
}
}
I am trying to develop a crossword puzzle with parse.com backend to sqlite backed. I have difficulty in converting the code.
Following code is the database table i had created.
public class puzzle extends SQLiteOpenHelper {
public static final String db_name = "crossword.db";
public static final String Table1_name = "puz";
public static final String Table2_name = "item";
public static final String Table3_name = "clue";
public puzzle(final Context context){
super(context, db_name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS" + Table1_name + "hash INTEGER, title TEXT, author TEXT,copyright TEXT,height INTEGER ,width INTEGER");
db.execSQL("CREATE TABLE IF NOT EXISTS"+ Table2_name + "hash INTEGER, x INTEGER ,y INTEGER, cell position INTEGER , black BOOLEAN , letter TEXT");
db.execSQL("CREATE TABLE IF NOT EXISTS" + Table3_name + "hash INTEGER, x INTEGER ,y INTEGER, cellposition INTEGER, cluenumber INTEGER, position INTEGER,clue TEXT");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + Table1_name);
db.execSQL("DROP TABLE IF EXISTS" + Table2_name);
db.execSQL("DROP TABLE IF EXISTS" + Table3_name);
onCreate(db);
}
public boolean insertitem(int hash, int x, int y, int cellposition, boolean black, String letter) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues itemvalues = new ContentValues();
itemvalues.put("hash", hash);
itemvalues.put("X", x);
itemvalues.put("Y", y);
itemvalues.put("CellPosition", cellposition);
itemvalues.put("Black", black);
itemvalues.put("Letter", letter);
long itemresult = db.insert(Table2_name, null, itemvalues);
if (itemresult == -1)
return false;
else
return true;
}
public boolean isinsertpuz(int hash,String title,String author,String copyright,int height,int width)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues puzvalues = new ContentValues();
puzvalues.put("hash",hash);
puzvalues.put("Title",title);
puzvalues.put("author",author);
puzvalues.put("copyright",copyright);
puzvalues.put("Height",height);
puzvalues.put("Width",width);
long puzresult = db.insert(Table1_name, null, puzvalues);
if (puzresult == -1)
return false;
else
return true;
}
public boolean isinsertclue(int hash,int x,int y,int cellposition,int cluenumber,String clue)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cluevalues = new ContentValues();
cluevalues.put("hash",hash);
cluevalues.put("X",x);
cluevalues.put("Y",y);
cluevalues.put("Cellposition",cellposition);
cluevalues.put("Cluenumber",cluenumber);
cluevalues.put("Clue",clue);
long clueresult=db.insert(Table3_name,null,cluevalues);
if(clueresult==-1)
return false;
else
return true;
}
public Cursor getpuzdata()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor puzquery=db.rawQuery("select * from" +Table1_name,null);
return puzquery;
}}
I want the following code in sqlite: I tried but it's showing some errorr, kindly help me!.
public CustomAdapter(Context context, int screenWidth, final int width,int screenHeight, int height, int hash, TextView clueTextView, TextView titleTextView){
this.context = context;
this.width = width;
this.height = height;
this.screenHeight = screenHeight;
this.screenWidth = screenWidth;
activity = (Activity)context;
this.hash = hash;
this.clueTextView = clueTextView;
this.titleTextView = titleTextView;
clueNumber = 0;
//cell count
count = width*height;
//to store each cell view
view = new View[count];
//contains solution
letterChar = new char[count];
clueAcross = new HashMap<>();
clueDown = new HashMap<>();
Log.d("parseSize", String.valueOf(letterChar.length));
//fetch data saved locally
query = ParseQuery.getQuery("Item").fromLocalDatastore();
query.whereEqualTo("hash", hash);
query.orderByAscending("cellPosition");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e == null)
for (ParseObject parseObject : objects) {
if(parseObject.getString("letter").equals(""))
letterChar[parseObject.getInt("cellPosition")] = ' ';
else
letterChar[parseObject.getInt("cellPosition")] = parseObject.getString("letter").charAt(0);
}
ParseQuery.getQuery("Clue").fromLocalDatastore().whereEqualTo("hash", CustomAdapter.this.hash).orderByDescending("clueNumber").getFirstInBackground(new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
if(e == null)
clueSize = object.getInt("clueNumber");
Log.d("clueNumber", String.valueOf(clueSize));
}
});
ParseQuery.getQuery("Clue").fromLocalDatastore().whereEqualTo("hash", CustomAdapter.this.hash).orderByAscending("cellPosition").findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null)
for (ParseObject object : objects) {
//int pos = (object.getInt("y")*width)+object.getInt("x");
if(object.getString("position").equals("Hor"))
clueAcross.put(object.getInt("cellPosition"), object.getString("clue"));
else
clueDown.put(object.getInt("cellPosition"), object.getString("clue"));
Log.d("clue", object.getInt("cellPosition")+" "+object.getString("clue")+" "+object.getString("position"));
}
//will populate the griview
Game.gridView.setAdapter(Game.customAdapter);
//to adjust layout on keyboard up
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
//dismiss progress dialog on UI thread
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Game.progress.dismiss();
}
});
}
});
}
});
//to fix clueNumber change on minimize and restore bug
if(clueNumber > clueSize)
clueNumber = 0;
}
#Override
public int getCount() {
return count;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
view[position] = convertView;
if(view[position] == null){
LayoutInflater layoutInflater = LayoutInflater.from(context);
view[position] = layoutInflater.inflate(R.layout.grid_cell, null);
view[position].setLayoutParams(new RelativeLayout.LayoutParams(screenWidth / width, screenHeight / height));
}
//to shade black on cells containing no letters
view[position].setBackgroundResource(R.drawable.shape);
TextView cellNumberTextView = (TextView)view[position].findViewById(R.id.cellNumber);
final EditText letter = (EditText)view[position].findViewById(R.id.letter);
/*letter.setCursorVisible(false);
letter.setClickable(false);
letter.setLongClickable(false);
letter.setFocusable(false);
letter.setSelected(false);
letter.setKeyListener(null);
letter.setBackgroundResource(android.R.color.transparent);*/
//letter.setText(Character.toString(letterChar[position]));
// cellNumberTextView.setTextSize(cellNumberTextView.getTextSize() / 1.5f);
//set clue number on cells
if(clueAcross.get(position) != null){
cellNumberTextView.setText(String.valueOf(clueNumber));
clueNumber++;
//to fix clueNumber change on minimize and restore bug
if(clueNumber > clueSize)
clueNumber = 0;
Log.d("clueNumber", position+" "+clueNumber+ " "+clueSize);
}
else if(clueDown.get(position) != null){
cellNumberTextView.setText(String.valueOf(clueNumber));
clueNumber++;
//to fix clueNumber change on minimize and restore bug
if(clueNumber > clueSize)
clueNumber = 0;
Log.d("clueNumber", position+" "+clueNumber+ " "+clueSize);
}
//to disable EditText operations on black cells
if(letterChar[position] == ' ') {
view[position].setBackgroundColor(Color.BLACK);
letter.setClickable(false);
letter.setLongClickable(false);
letter.setFocusable(false);
letter.setSelected(false);
letter.setKeyListener(null);
}else
view[position].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//update clues on view click
clueTextView.setText(getClueDown(position));
titleTextView.setText(getClueAcross(position));
//to open keyboard and focus on the letter to edit
letter.requestFocus();
letter.setCursorVisible(true);
((InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(letter, InputMethodManager.SHOW_IMPLICIT);
}
});
//update clues on letter click
letter.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
letter.setText("");
clueTextView.setText(getClueDown(position));
titleTextView.setText(getClueAcross(position));
}
}
});
//check value and change color of cell accordingly
letter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//letter.setText(s.toString().toUpperCase());
if(s.toString().isEmpty())
return;
Log.d("letter", "input "+s.toString()+"position "+String.valueOf(position)+Character.toString(letterChar[position]));
if (s.toString().equals(Character.toString(letterChar[position]))) {
view[position].setBackgroundResource(R.drawable.correct);
focusNext(position);
}
else
view[position].setBackgroundResource(R.drawable.wrong);
}
#Override
public void afterTextChanged(Editable s) {
/* if(s.toString().isEmpty())
return;*/
//view[0].setBackgroundResource(R.drawable.correct);
}
});
return view[position];
}
//to focus next cell
public void focusNext(int position) {
for (int i = position; i < count; i++) {
if (letterChar[i+1] == ' ')
continue;
else {
EditText editText = (EditText) ((ViewGroup) view[i + 1]).getChildAt(0);
editText.requestFocus();
((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
return;
}
}
}
//get ACROSS clue based on position
public String getClueAcross(int position){
for(int i=position; i>=0; i--)
if(clueAcross.get(i) != null)
return "(across): "+clueAcross.get(i);
return "";
}
//get DOWN clue based on position
public String getClueDown(int position){
for(int i=position; i>=0; i-=width)
if(clueDown.get(i) != null)
return "(down): "+clueDown.get(i);
return "";
}
#Override
public Object getItem(int position) {
return view[position];
}
#Override
public long getItemId(int position) {
return position;
}
}
The following code is how i tried to change the code from parse.com to sqlite
public class CustomAdapter extends BaseAdapter {
int count, hash;
int width, height, screenWidth, screenHeight;
Activity activity;
Context context;
private static final String SELECTitem_SQL = "SELECT * FROM item";
private static final String SELECTpuz_SQL = "SELECT * FROM puz";
private static final String SELECTclue_SQL = "SELECT * FROM clue";
private SQLiteDatabase db,db1 ;
puzzle ca=new puzzle(context);
char[] letterChar;
HashMap<Integer, String> clueAcross, clueDown;
TextView clueTextView, titleTextView;
int clueNumber, clueSize;
View view[];
public CustomAdapter(Context context, int screenWidth, final int width,int screenHeight, int height, int hash, TextView clueTextView, TextView titleTextView) {
this.context = context;
this.width = width;
this.height = height;
this.screenHeight = screenHeight;
this.screenWidth = screenWidth;
activity = (Activity) context;
this.hash = hash;
this.clueTextView = clueTextView;
this.titleTextView = titleTextView;
clueNumber = 0;
letterChar = new char[100];
//cell count
count = width * height;
//to store each cell view
view = new View[count];
//contains solution
letterChar = new char[count];
clueAcross = new HashMap<>();
clueDown = new HashMap<>();
Log.d("parseSize", String.valueOf(letterChar.length));
Cursor c1=db.rawQuery(SELECTitem_SQL,null);
Cursor c2=db.rawQuery(SELECTclue_SQL,null);
c1.moveToFirst();
c2.moveToFirst();
db= openOrCreateDatabase("item", null);
db1=openOrCreateDatabase("clue",null);
String hashid=c1.getString(0);
String cluehash=c2.getString(0);
String cluenum=c2.getString(4);
String hashpos=c1.getString(3);
String hashletter=c1.getString(5);
String hashblack=c1.getString(4);
int id=hashid.length();
for(int i=0;i<id;i++)
{
if(hashletter== "")
{
letterChar[Integer.parseInt(hashpos)]=' ';
}
else
{
letterChar[Integer.parseInt(hashpos)]=hashletter.charAt(0);
}
}
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return null;
}
}
This is my code to convert from parse to sqlite but when i build the project it stays still.
I'm not sure if this helps you but there is a sql syntax error in your code:
db.execSQL("CREATE TABLE IF NOT EXISTS " + Table1_name + " (hash INTEGER, title TEXT, author TEXT,copyright TEXT,height INTEGER ,width INTEGER)");
db.execSQL("CREATE TABLE IF NOT EXISTS "+ Table2_name + " (hash INTEGER, x INTEGER ,y INTEGER, cell position INTEGER , black BOOLEAN , letter TEXT)");
db.execSQL("CREATE TABLE IF NOT EXISTS " + Table3_name + " (hash INTEGER, x INTEGER ,y INTEGER, cellposition INTEGER, cluenumber INTEGER, position INTEGER,clue TEXT)");
you missed "(" before "hash",a space after "EXISTS" and ")" at the end of each statement