How to fetch Sqlite data using the user input? - java

Currently i am working with an app that recommends the colleges to the students by taking the input as their aggregate Percentage. In the first activity I have one edit text used for percentage. In second activity I want to recommend the colleges according to input percentage for that i am using explicit intent (to pass the percentage from first activity to second) but i am not familiar with how to use that percentage to recommend the colleges list which suits the entered percentage.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button submitData;
EditText percentage;
public String pData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
setContentView(R.layout.activity_main);
percentage = (EditText)findViewById(R.id.studentpercentage);
submitData = (Button)findViewById(R.id.submitdetails);
submitData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
pData = percentage.getText().toString();
Intent intent = new Intent(getApplicationContext(), DisplayList.class);
intent.putExtra("Percentage", pData);
startActivity(intent);
}
}
);
}
}
DisplayList.java
public class DisplayList extends AppCompatActivity {
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
setContentView(R.layout.activity_display_list);
TextView percentage = (TextView)findViewById(R.id.textView);
Bundle bundle = getIntent().getExtras();
if (bundle.getString("Percentage")!=null) {
String per = (String)bundle.get("Percentage");
}
this.listView = (ListView)findViewById(R.id.listview);
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this);
databaseAccess.open();
List<String> colleges = databaseAccess.getColleges();
databaseAccess.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,colleges);
this.listView.setAdapter(adapter);
}
}
DatabaseAccess.java
/**
* Read all colleges from the database.
*/
public List<String> getColleges() {
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT * FROM Ahmednagar", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(1));
list.add(cursor.getString(2));
list.add(cursor.getString(3));
list.add(cursor.getString(4));
list.add(cursor.getString(5));
cursor.moveToNext();
}
cursor.close();
return list;
}

Pass the per variable in getColleges() method .
like- getColleges(per);
and change the method and query in db file
like -
public List<String> getColleges(String per) {
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT * FROM Ahmednagar Where Perentage="+per, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(1));
list.add(cursor.getString(2));
list.add(cursor.getString(3));
list.add(cursor.getString(4));
list.add(cursor.getString(5));
cursor.moveToNext();
}
cursor.close();
return list;
}

Related

Cardview Items in Recyclerview temporarily duplicating previous entries when adding new data

sing the dialogfragment to get the user input, while I am capable of updating the mainactivity using the ((MainActivity)getActivity()).storeDataInArrays(); command (This is in order to refresh the recyclerview to display the newly added contact).
However now there seems to be this new issue cropping up where only temporarily, instead of only showing the newly updated contact, it shows adds all of the previous contacts as well.Until I exit and enter the Mainactivity.
This is a demonstration of what's happening.
This is the Mainactivity
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
//widgets
public ImageButton eAddContact;
RecyclerView recyclerView;
DatabaseHelper myDB;
ArrayList<String> Contact_id, Contact_Name, Contact_Number;
CustomAdapter customAdapter;
Button btnEnterContact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eAddContact = findViewById(R.id.btnAddContact);
eAddContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick:opening dialog");
Dialog_AddContact dialog = new Dialog_AddContact();
dialog.show(getSupportFragmentManager(), "Add Contact Dialog");
}
});
//Toast.makeText(getApplicationContext(),"##",Toast.LENGTH_SHORT).show();
myDB = new DatabaseHelper(MainActivity.this);
Contact_id = new ArrayList<>();
Contact_Name = new ArrayList<>();
Contact_Number = new ArrayList<>();
recyclerView = findViewById(R.id.RecyclerView);
customAdapter = new CustomAdapter(MainActivity.this, Contact_id, Contact_Name, Contact_Number);
storeDataInArrays();
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}
void storeDataInArrays() {
Cursor cursor = myDB.getEveryone();
if (cursor.getCount() == 0) {
//Add blank page
} else {
while (cursor.moveToNext()) {
Contact_id.add(cursor.getString(0));
Contact_Name.add(cursor.getString(1));
Contact_Number.add(cursor.getString(2));
}
}
customAdapter.notifyDataSetChanged();
}
}
and This is the dialogfragment's enter contact button where I call the Mainactivity fuction
btnEnterContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ContactInfo ContactInfo;
try {
Log.d(TAG, "onClick: Entering Contact");
ContactInfo = new ContactInfo(-1,etName.getText().toString(),etPhonenumber.getText().toString());
Toast.makeText(getContext(),ContactInfo.toString(),Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getContext(),"Error Creating Contact",Toast.LENGTH_SHORT).show();
ContactInfo = new ContactInfo(-1,"error","0");
}
DatabaseHelper databaseHelper = new DatabaseHelper(getContext());
boolean success = databaseHelper.addOne(ContactInfo);
Toast.makeText(getContext(),"Success="+success,Toast.LENGTH_SHORT).show();
((MainActivity)getActivity()).storeDataInArrays();
getDialog().dismiss();
}
});
I would really appreciate any help in figuring out how to solve this.

Query a specific column in the database

I have 2 activities. The first one displays a list of data obtained from the MySQL table. By clicking on a list item, the next activity on which information about the pressed item will be displayed will be opened. But for this I need to create a new database query and get only the column that I passed as the "id" from listview
MainAcitvity
public class MainActivity extends AppCompatActivity {
ListView listView;
DataBase dataBase;
SQLiteDatabase sqLiteDatabase;
FloatingActionButton fabMain;
MySimpleAdapter simpleCursorAdapter;
Cursor cursor;
Task taskClass;
TextView tvTitleItemList, tvTextItemList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fabMain = findViewById(R.id.fab_main);
listView = findViewById(R.id.rv_list);
tvTitleItemList = findViewById(R.id.tv_title_item_list);
tvTextItemList = findViewById(R.id.tv_text_item_list);
dataBase = new DataBase(this);
sqLiteDatabase = dataBase.getWritableDatabase();
//next activity and add in database
fabMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
});
//get
cursor = sqLiteDatabase.query(dataBase.DATABASE_TABLE, null, null, null, null, null, null);
simpleCursorAdapter = new MySimpleAdapter(MainActivity.this, cursor, 0);
listView.setAdapter(simpleCursorAdapter);
//delete
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, TaskActivity.class );
String value = simpleCursorAdapter.id;
intent.putExtra("id", value);
startActivity(intent);
}
});
}
#Override
protected void onRestart() {
super.onRestart();
simpleCursorAdapter = new MySimpleAdapter(MainActivity.this, cursor, 0);
listView.setAdapter(simpleCursorAdapter);
}
activity in which you need to re-create a database query by id
public class TaskActivity extends AppCompatActivity {
TextView tvTitleActivityTask, tvTextActivityTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
tvTitleActivityTask = findViewById(R.id.tv_title_activity_task);
tvTextActivityTask = findViewById(R.id.tv_text_activity_task);
Intent intent = getIntent();
intent.getExtras();
String valueId = intent.getStringExtra("id");
}
}

Send listView data from one activity to another

I'm trying to figure out how to get the data from a listView, store it in an Array, and be able to access that array of data in another activity. Would I do an Intent for this and pass it as an extra? I've searched around but haven't gotten a clear answer. I want to be able to access that array of data so that I can randomly display it in another activity.
listView.java
public class ListView extends AppCompatActivity {
private static final String TAG = "ListView";
private EditText editText;
private android.widget.ListView listView;
DatabaseHelper mDatabaseHelper;
Button btnAdd;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
mDatabaseHelper = new DatabaseHelper(this);
btnAdd = (Button) findViewById(R.id.btnAdd);
editText = (EditText) findViewById(R.id.editText);
listView = (android.widget.ListView) findViewById(R.id.lv);
ArrayList<String> list = getIntent().getStringArrayListExtra("myList");
android.widget.ListView lv = (android.widget.ListView) findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
//Takes user back to the main activity after clicking on back arrow
ImageView ivBack = (ImageView) findViewById(R.id.ivBackArrow);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: pressed back arrow");
Intent intent = new Intent(ListView.this, MainActivity.class);
startActivity(intent);
}
});
//Adds new hashtag to list and prompts if nothing is entered
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
addData(newEntry);
editText.setText("");
} else {
toastMessage("you must put something in the text field");
}
}
});
populateListView();
}
/**
* Adds new data into the Database
* #param newEntry
*/
public void addData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Successfully inserted");
recreate();
} else {
toastMessage("Whoops, something went wrong");
}
}
/**
* Default toastMessage
* #param message
*/
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
/**
* Populate listView with data and create listener to navigate to editDeleteList
*/
private void populateListView() {
Log.d(TAG, "populateListView: displaying data in the listview");
//get data and append to list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()) {
//get the value from the database in column 1
//set it to the arraylist
listData.add(data.getString(1));
}
//create arraylist and set it to the adapter
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
listView.setAdapter(adapter);
//set onclick listen to edit activity
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String name = adapterView.getItemAtPosition(position).toString();
Log.d(TAG, "onItemClick: you clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while (data.moveToNext()) {
itemID = data.getInt(0);
}
if (itemID > -1) {
Log.d(TAG, "onItemID: the ID is: " + itemID);
Intent editScreenIntent = new Intent(ListView.this, EditDeleteList.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
} else {
toastMessage("No ID found");
}
}
});
}
/**
* Updates the listView after navigating back from EditDeleteList activity
*/
#Override
protected void onResume() {
super.onResume();
populateListView();
}
}
Get data from listView:
public static String[] getStringArray(ListAdapter adapter){
String[] a = new String[adapter.getCount()];
for (int i = 0; i < a.length; i++)
a[i] = adapter.getItem(i).toString();
return a;}
String[] array = getStringArray(myListView.getAdapter());
Send array from activity to another one:
Intent intent = new Intent(context, Class.class);
intent.putExtra("mylist", array);
Get it back within another activity:
ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");
You can pass an ArrayList<E> the same way, if the E type is Serializable.
I am assuming 1) You are modifying the ListView, 2) On press of button you want to go to another activity and have the data updated from listview in Activity2. From the ListView's adapter, you can create an interface (UpdateListListener) which will be implemented by the Activity1. Whenever you press button(after editing) you just a)Call notifyDatasetChanged() and on the implemented method listener(onUpdatedList()) you just send the list to the other activity with intent. Since List is an object you need to send the intent as below:
Intent intent = new Intent(this,Activity2.class);
intent.putExtra("myList", ListOfItems);
startActivity(intent);
Where ListOfItems implements Parcelable. You need to study how Parcelable works.

cannot infer type arguments for ArrayAdapter<> when retrieving data from a database

My code is here please tell me what is the problem.
when i want to retrieve data from SQlite database the it give me the following error.
Please someone tell me what is the problem in my code
public class ViewData extends AppCompatActivity {
DatabaseHelper mDb;
TextView EList;
Button mBtn;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_data);
listView = (ListView) findViewById(R.id.listView);
mBtn = (Button) findViewById(R.id.buttonList);
mDb=new DatabaseHelper(this);
view1All();
}
public void view1All() {
mBtn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<String> theList=new ArrayList<>();
Cursor res = mDb.getAllData();
if(res.getCount() == 0) {
// show message
// showMessage("Error","Nothing found");
// return;
}
while (res.moveToNext()) {
theList.add(res.getString(1));
ListAdapter listAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
listView.setAdapter(listAdapter);
}
}
}
);
}
}

How to get the arraylist out android studio

I am unable to get my ArrayList out when it's on a different page. I would like to get the ArrayList out Android Studio.
This is CartActivity class:
public class CartActivity extends AppCompatActivity {
private ArrayList<CartItem> cartList;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
listView = (ListView) findViewById(R.id.listView);
CartAdapter adapter = null;
cartList = new ArrayList<>();
adapter = new CartAdapter(this, R.layout.adapter_cart_item, cartList);
listView.setAdapter(adapter);
}
}
This is ProductActivity class. It's where the data is being stored into the ArrayList:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product);
myDB = new DatabaseHelper(ProductActivity.this);
textViewPrice = (TextView) findViewById(R.id.textViewPrice);
textViewInfo = (TextView) findViewById(R.id.textViewInfo);
textViewName = (TextView) findViewById(R.id.textViewName);
ivProduct = (ImageView) findViewById(R.id.ivProduct);
btnAddToCart = (Button) findViewById(R.id.btnAddToCart);
spinnerQuantity = (Spinner) findViewById(R.id.spinnerQuantity);
Intent in = getIntent();
Bundle b = in.getExtras();
userID = b.getString("userID");
productID = b.getInt("productID");
Cursor results = myDB.checkProduct();
if (results.getCount() == 0) {
Toast.makeText(getApplicationContext(), "Error: no data found!",
Toast.LENGTH_SHORT).show();
return;
} else {
StringBuffer buffer = new StringBuffer();
while (results.moveToNext()) {
id = results.getInt(0);
name = results.getString(1);
price = results.getString(2);
info = results.getString(4);
quantity = Integer.parseInt(results.getString(5));
image = results.getBlob(6);
if (id == productID) {
textViewName.setText(name);
textViewInfo.setText(info);
textViewPrice.setText("S$" + price);
int[] quantityValues = new int[quantity + 1];
int counter = 0;
for (int i = 0; i < quantityValues.length; i++) {
quantityValues[i] = counter;
counter++;
quantityList.add(Integer.toString(quantityValues[i]));
}
Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
ivProduct.setImageBitmap(bitmap);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, quantityList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerQuantity.setAdapter(adapter);
}
}
}
}
public void addCart(View v) {
cartList.add(new CartItem(name, price,spinnerQuantity.getSelectedItem().toString(), image, id));
Intent productListIntent = new Intent(this, CartActivity.class);
startActivity(productListIntent);
}
You should impliment Serializable in CartItem class and then pass from ProductActivity to CartActivity . Like this :
ProductActivity class.
Intent productListIntent= new Intent(this, CartActivity .class);
productListIntent.putExtra("cartlist", ArrayList<CartItem>mcartItem);
startActivity(productListIntent);
and in CartActivity class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
ArrayList<CartItem> mycart= new ArrayList<CartItem>();
mycart= (ArrayList<CartItem>)getIntent().getSerializableExtra("cartlist");
listView = (ListView) findViewById(R.id.listView);
CartAdapter adapter = null;
adapter = new CartAdapter(this, R.layout.adapter_cart_item, mycart);
listView.setAdapter(adapter);
}
It's not the best practice, but you can make your arrayList
public static ArrayList list;
Then you can access it from ather activity using {class_name}.list
You have to pass your list of your data via intent(as Intent is a message passing Object) From ! activity to another activity. For that you have to make that class Parcable or Serializable . How to make a class Parcable in andriod studio read this answer. Then put thah class into the intent that you are passing to startActivity() method like
intent.putParcelableArrayListExtra("key",your_list);
or
intent.putExtra("key",your_class)// incase of single object
then get it to the onCreate() method of second activity like
getIntent().getParcelableArrayListExtra("your_key")
or
getIntent().getParcelableExtra()// incase of single object
Hope it will help your

Categories