Sqlite databse puts data in the wrong columns - java

I'm having a problem with my database when I try to add data from the simulator it puts it in the wrong column. I understand that it begins from 0 like (1 column = 0, 2 column = 1....)
I think I set it to 1 to put the data in the 2 columns but instead it puts it in the 3 columns but when set it to "0" it adds data the first column like it supposed to. Anybody has any ideas why it might be happening?
package com.example.laivumusis;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class ViewListData extends AppCompatActivity {
KlausimynoDatabaseHelper myDB;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editlistview_layout);
ListView listView = (ListView) findViewById(R.id.listView);
myDB = new KlausimynoDatabaseHelper(this);
ArrayList<String> theList = new ArrayList<>();
Cursor data = myDB.getListContents();
if (data.getCount() == 0) {
Toast.makeText(ViewListData.this,"Database tuščias!",Toast.LENGTH_LONG).show();
}else{
while (data.moveToNext()){
theList.add(data.getString(1));
ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,theList);
listView.setAdapter(listAdapter);
}
}
}
}

Don't use the index of the column like this:
theList.add(data.getString(1));
Use the method getColumnIndex() by passing the name of the column, because the order of the columns may not be what you think it is.
So change to this:
theList.add(data.getString(data.getColumnIndex("columnName")));
Replace columnName with the name of the column that you want.

Related

Unable to display data in recycler view from room db

Getting error at NewActivity, as getting error while adding the data in array list and loading it to recycler view. Iam working on a project where I have to load Room data in recycler view. I am getting an error in for loop .. tried using foreach still getting tge same error. Error is showing while using add method to load a data from list to arraylist
package com.app.mycontacts;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import com.app.mycontacts.AddContactActivity.AddContactActivity;
import com.app.mycontacts.Data.ContactDetails;
import com.app.mycontacts.Data.ContactRepository;
import com.app.mycontacts.Data.MyAdapterClass;
import com.app.mycontacts.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
public class NewActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
ArrayList<ContactDetails> contactarrayList;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView= findViewById(R.id.reyclerview);
new LoadDataTask().execute();
}
class LoadDataTask extends AsyncTask<Void,Void,Void> {
ContactRepository contactRepository;
List<ContactDetails> contactList1;
#Override
protected void onPreExecute() {
super.onPreExecute();
contactRepository = new ContactRepository(getApplicationContext());
}
#Override
protected Void doInBackground(Void... voids) {
contactList1=contactRepository.getContactsDetails();
contactarrayList= new ArrayList<ContactDetails>();
for(int i=0; i<=contactList1.size();i++){
contactarrayList.add(contactList1.get(i));
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
super.onPostExecute(unused);
recyclerView.setLayoutManager(new LinearLayoutManager(NewActivity.this));
MyAdapterClass myAdapterClass= new MyAdapterClass(NewActivity.this,contactarrayList);
recyclerView.setAdapter(myAdapterClass);
}
}
}
Tried debugging the code, app is getting crash at the above stage.. Expecting to display the data inserted at room db.
You are indexing wrong in the loop.
The size of the list is 4 but Java indexes from 0. So if you have 4 elements it goes [0], [1], [2], [3]
for(int i=0; i<=contactList1.size();i++){
contactarrayList.add(contactList1.get(i));
}
What you are doing is reaching for the fifth element - [0], [1], [2], [3], [4].
This will work:
for(int i=0; i < contactList1.size();i++){
contactarrayList.add(contactList1.get(i));
}
But you don't need to iterate it, you should be able to just call .addAll.
contactarrayList.addAll(contactList1);

unable to search database from button.setOnClick .getText as String becomes null

I am making android app that takes user input from EditText on press of button from button.setOnClick() and use the string.getText() to search the database. But the string becomes null and no way i can send it
DbBackend.class where the search function is.
I checked and database works fine on static query which you can set to = "xyz" but no way i am able to use the user input to query the database.
Here is my code: MainActivity.java
package com.vadhod.dictcopy;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.sql.Array;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import static android.app.PendingIntent.getActivity;
public class MainActivity extends AppCompatActivity {
TextView textView;
EditText searchBar;
Button searchButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DbBackend dbBackend = new DbBackend(MainActivity.this);
searchBar = (EditText) findViewById(R.id.searchBar);
searchButton = (Button) findViewById(R.id.searchButton);
textView = (TextView)findViewById(R.id.textView);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
String input = searchBar.getText().toString();
ArrayList<String> terms = dbBackend.getList(input);
StringBuilder builder = new StringBuilder();
for (String details : terms) {
builder.append(details + "\n");
}
textView.setText(builder.toString());
}catch (Exception e){
e.printStackTrace();
}
}
});
}
}
DbBackend.java
package com.vadhod.dictcopy;
import ...
public class DbBackend extends DatabaseObject {
public DbBackend(Context context){
super(context);
}
public ArrayList<String> getList(String search){
ArrayList<String> kWords = new ArrayList<String>();
String searchQuery = "SELECT kName FROM dictionary WHERE eName LIKE '%" + search + "%'";
try {
Cursor kCursor = this.getDbConnection().rawQuery(searchQuery, null);
if (kCursor != null){
kCursor.moveToFirst();
for (int i = 0; i < kCursor.getCount(); i++ ){
String sword = kCursor.getString(kCursor.getColumnIndexOrThrow("kName"));
kWords.add(sword);
kCursor.moveToNext();
}
kCursor.close();
return kWords;
}
return kWords;
}catch (Exception e){
e.printStackTrace();
}
return kWords;
}
}
Any help please on how to use the string when user press the search button and search that through the database and return the query?
Updated the moved code
Assuming that inside the searchButton.setOnClickListener(new View.OnClickListener() {...}); the search is working, and outside - not. The problem is your
//Option 1 not working
ArrayList<String> terms2 = dbBackend2.getList(input);
is called during the Activity setup before any view is shown to the user. So, the input is not filled at that time. You have to move this code into an onclick listener, like you did in the code above these lines.
Or provide some other source for the input.
Upd:
For the NullPointer: in your layout file activity_main you need to have a TextView with id textView. Because you do the following:
// find the textview in the layout
textView = (TextView)findViewById(R.id.textView);
// do the search, get results
...
// set textview's text, at this moment textView must not be null
textView.setText(kbuilder.toString());

how to find duplicate contacts in list View

I have developed app that access contacts via Content Resolver.It show all the contacts in one list view even duplicate contacts also shown on same list view But i want to show duplicate contacts in other list view so that i can delete them according to my wish easily. Kindly Help me. Ill be thankful to you cordially .here is sample code.
package com.example.contentprovider;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends AppCompatActivity {
// Cursor Adapter for storing contacts data
SimpleCursorAdapter adapter;
// List View Widget
ListView lvContacts;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Init ListView
lvContacts = (ListView) findViewById(R.id.lvContacts);
// Initialize Content Resolver object to work with content Provider
ContentResolver cr = getContentResolver();
// Read Contacts
Cursor c = cr.query(ContactsContract.Contacts.CONTENT_URI,
new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME }, null, null,
null);
// Attached with cursor with Adapter
adapter = new SimpleCursorAdapter(this, R.layout.row, c,
new String[] { ContactsContract.Contacts.DISPLAY_NAME },
new int[] { R.id.lblName });
// Display data in listview
lvContacts.setAdapter(adapter);
}
}
I would suggest you add all contact into list and remove duplicate by hashset . because hashset does not allow duplicate elements.
psedo code:---
1. Once get all object like name,phone number from contentResolver then add those string objet into arraylist
2. After that pass taht list to hashset so duplicate will be removed.
ArrayList<String> values=new ArrayList<String>();
HashSet<String> hashSet = new HashSet<String>();
hashSet.addAll(values);
values.clear();
values.addAll(hashSet);
it might be helpful for you .
find Duplicate Contact from Contact ArrayList
private ArrayList<PhoneContact> findDuplicates1(ArrayList<PhoneContact> phoneContacts) {
int i;
ArrayList<PhoneContact> list2 = new ArrayList<>();
PhoneContact contact;
int count ;
for (i = 0; i < phoneContacts.size() ; i++){
String contact1 = phoneContacts.get(i).getContactNumber();
contact = phoneContacts.get(i);
count = 0;
list2.add(contact);
for (int j = i+1 ;j < phoneContacts.size() ; j++ )
{
String contact2 = phoneContacts.get(j).getContactNumber();
if (contact1.equals(contact2) || contact1.equals("+91"+contact2) || contact2.equals("+91"+contact1)){
phoneContacts.get(j).setCheck(true);
PhoneContact contact11 = phoneContacts.get(j);
count = 1;
list2.add(contact11);
phoneContacts.remove(j);
}
}
if (count == 0)
{
list2.remove(contact);
count=0;
}
}
return list2;
}
here Just pass your Contact ArrayList and return list Of Duplicate contact

Unable to get list items correct code using Java

I am trying to create a list view in Java that allows each list item to open a web url address but I can not seem to get the code right. Please can some one show me where IO going wrong.
package com.sasquatchapps.hydraquip10.bestofmonsterquest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Season1Activity extends Activity{
private String episodes[] = {"America's Loch Ness Monster","Sasquatch Attack",
"Giant Squid Found","Birdzilla","Bigfoot","“Mutant K9","Lions in the Backyard","Gigantic Killer Fish","Swamp Beast","Russia's Killer Apemen","Unidentified Flying Creatures","The Real Hobbit",
"Giganto: The Real King Kong","American Werewolf"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter = new
ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, episodes);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(this, "Item clicked;" + episodes[position], Toast.LENGTH_SHORT).show();
if (position == 0) {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/watch?v=o7-RdxrCFAg"));
startActivity(intent);
}
}
}
You have some errors - Where is your listview? Modify your code
1) create listview -
ListView myList;
2) In your onCreate assign this list:
myList = (ListView) findViewById(R.id.my_list);
3) Set adapter to your list:
myList.setAdapter(adapter);

Android Spinner not showing up

Can anyone tell me why my spinners are not showing up? I'm doing an exercise and I don't understand why my spinners show no items at all. any suggestions?
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import java.util.*;
public class Length extends Activity{
private Spinner spi1,spi2,cmbOpciones;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.length);
//Spinner1
List<String> imperialunits = new ArrayList<String>();
imperialunits.add("inch");
imperialunits.add("foot");
imperialunits.add("yard");
imperialunits.add("mile");
ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, imperialunits);
spi1=(Spinner)findViewById(R.id.spinner1);
adaptador.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spi1.setAdapter(adaptador);
//Spinner2
final String[] SIunits =
new String[]{"km","m","cm"};
ArrayAdapter<String> adaptador2 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, SIunits);
spi2 = (Spinner)findViewById(R.id.spinner2);
adaptador2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spi2.setAdapter(adaptador2);
//Spinner 3
final String[] datos = new String[]{"Elem1","Elem2","Elem3","Elem4","Elem5"};
ArrayAdapter<String> adaptador3 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, datos);
cmbOpciones = (Spinner)findViewById(R.id.CmbOpciones);
adaptador.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cmbOpciones.setAdapter(adaptador3);
}
}
Your code to populate the Spinners looks fine (I think),maybe your problem is on your layout xml?, but why don't you try using an array of strings instead? like here, plus you get to use resource values, I personally think its better not creating stuff like that at runtime.
I tested your code and works perfectly. I agree, it must be something wrong in your xml file.

Categories