Unsorted saving of data from php to sqlite - android

I am saving receiving data from external server. Now, this is the sample data that I am receiving:
Now what happens is that when I save them to mysqlite db, it doesn't the follow the order of id, Here's the sample of it:
Here's my code for fetching data:
private class getData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
Http sh = new Http();
try {
String URLS = "http://localhost/sample.php?date="+datePHP+"&gametype="+gamePHP+"&time="+timePHP+"&bettype="+typePHP;
String jsonStr = sh.makeServiceCall(URLS);
if(jsonStr != null){
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray sims = (JSONArray)jsonObj.get("mmi");
for (int i = 0; i < sims.length(); i++) {
JSONObject c = sims.getJSONObject(i);
String betid = c.getString("id");
String betnumber = c.getString("betnumber");
String betamount = c.getString("betamount");
boolean insertBets = databaseHelper.addBets(betid, betnumber, betamount, timePHP, datePHP,gamePHP,typePHP);
if (insertBets){
System.out.println("SAVED");
}else{
System.out.println("UPDATED");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
runOnUiThread(() -> {
populatelistview();
});
}
}
Code for saving to sqlite:
public boolean addBets(String betid, String betnum, String betAmt, String betTime, String betDate, String gameType, String betType) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("betid", betid);
contentValues.put("betNum", betnum);
contentValues.put("betAmt", betAmt);
contentValues.put("betTime", betTime);
contentValues.put("betDate", betDate);
contentValues.put("gameType", gameType);
contentValues.put("betType", betType);
String sql = "SELECT * FROM betsx WHERE betNum ='" + betnum + "' AND betTime ='" + betTime + "' AND betDate = '" + betDate + "' AND gameType ='" + gameType + "' AND betType ='" + betType + "'";
Cursor cursor = db.rawQuery(sql, null);
db.insert("betsx", null, contentValues);
System.out.println(betnum + "//" + betAmt);
return true;
}

Related

Android Java Cannot showing database table and cannot resolve method 'setText(java.sql.Date)'

I am new in android java world. Now, I'm trying to display data table from MSSQL in ArrayList to ListView in android. I'm trying to make the following code something like this in ScanResult Class;
public class FillList extends AsyncTask<String,String,String>{
String z ="";
List<Map<String,String>> prolist = new ArrayList<Map<String,String>>();
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String s) {
Toast t = Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT);
t.show();
}
#Override
protected String doInBackground(String... strings) {
try{
ConnectionHelper connectionHelper = new ConnectionHelper();
connect = connectionHelper.connectionclass();
if(connect==null){
z ="Connection error";
} else {
String query = "SELECT LabelNo " +
", Qty " +
", Rmrks " +
", ScanDate " +
"FROM dbo.shikakarikensa " +
"WHERE CAST(ScanDate AS DATE) = CAST(GETDATE()-1 AS DATE) " +
"AND Type = 'I' " +
"ORDER BY ScanDate DESC";
PreparedStatement ps = connect.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()){
CustomListViewValueArr.add(new ScanModel(rs.getString("LabelNo"),rs.getInt("Qty"),rs.getString("Rmrks"),rs.getString("ScanDate")));
}
z="Today's scan result list";
}
} catch (Exception ex){
z = ex.getMessage();
}
return z;
}
}
But I get an error Cannot resolve method 'setText(java.sql.Date)' in the CustomAdapter Class, which is in the line;
holder.txtscandate.setText(scanModel.getScanDate());
scanModel = null;
scanModel=(ScanModel) mList.get(position);
holder.txtlabelno.setText(scanModel.getLabelNo());
holder.txtqty.setText(scanModel.getQty());
holder.txtrmrks.setText(scanModel.getRmrks());
holder.txtscandate.setText(scanModel.getScanDate());
I tried also comment the ScanDate line but the data does not showing in the ListView.
This is Model Class
public class ScanModel {
String LabelNo, Rmrks;
int Qty;
Date ScanDate;
public ScanModel(String labelno, int qty, String rmrks, Date scandate) {
LabelNo = labelno;
Qty = qty;
Rmrks = rmrks;
ScanDate = scandate;
}
public String getLabelNo() { return LabelNo; }
public int getQty() { return Qty; }
public String getRmrks() { return Rmrks; }
public Date getScanDate() { return ScanDate; }
}

Android AsyncTask class Hanged my Application why?

i call MyTask().execute(); in onCreate() of MainAcivity Class in my application. it Busy or Hang my application for long time. please help me why? i want my work in background so that it can't disturb my app. Why my app become busy and unresponsive?
Class code is below:
private class MyTask extends AsyncTask<String, Integer, String> {
// Runs in UI before background thread is called
#Override
protected void onPreExecute() {
super.onPreExecute();
// Do something like display a progress bar
}
// This is run in a background thread
#Override
protected String doInBackground(String... params) {
checkUser();
return "";
}
// This is called from background thread but runs in UI
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// Do things like update the progress bar
}
// This runs in UI when background thread finishes
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Do things like hide the progress bar or change a TextView
}
}
checkUser() method code is below
private void checkUser(){
// now here we convert this list array into json string
final String server_url="http://www.xxxx.com/TruCaller/check_user.php"; // url of server check this 100 times it must be working
// volley
StringRequest stringRequest=new StringRequest(Request.Method.POST, server_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response)
{
final String result=response.toString().trim();
if(result.equals("not found")){
//Toast.makeText(MainActivity.this,"Wait...",Toast.LENGTH_LONG).show();
// Log.d("responsedd", "result not found fffffffff: "+result);
getContacts2();
}else{
}
// Log.d("responsedd", "result : "+result); //when response come i will log it
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
error.printStackTrace();
error.getMessage(); // when error come i will log it
}
}
)
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("identifier", UIDD);
Log.d("responsedd", "result not found ggggggggggg: "+ UIDD);
return params;
}
};
Vconnection.getnInstance(this).addRequestQue(stringRequest); // vConnection i claas which used to connect volley
}
getContacts2() method code is below:
public void getContacts2() {
if (!mayRequestContacts()) {
return;
}
// contactList = new ArrayList<String>();
String phoneNumber = null;
String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output;
ContentResolver contentResolver = getContentResolver();
cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
// Iterate every contact in the phone
if (cursor.getCount() > 0) {
counter = 0;
while (cursor.moveToNext()) {
output = new StringBuffer();
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
String phoneC = "", adressC = "", emailC = "",country_code="";
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
Bitmap bitmap = null;
String image = "";
if (hasPhoneNumber > 0) {
////////////////////Phone numbers with this name..... 2 Testing ....////////////////
String phoneNumber2 = "";
final String[] projection = new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.TYPE,};
final Cursor phone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, ContactsContract.Data.CONTACT_ID + "=?", new String[]{String.valueOf(contact_id)}, null);
if (phone.moveToFirst()) {
final int contactNumberColumnIndex = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA);
phoneC = "";
while (!phone.isAfterLast()) {
////////////////////////////////////////////
String x = phone.getString(contactNumberColumnIndex);
bitmap = retrieveContactPhoto(MainActivity.this, x);
String countryCode = countryCode(phone.getString(contactNumberColumnIndex));
country_code = countryCode;
// String swissNumberStr = "03348633664";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.createInstance(getApplicationContext());
Phonenumber.PhoneNumber pNumberProto;
String phoneVerfid="";
try {
pNumberProto = phoneUtil.parse(phone.getString(contactNumberColumnIndex), countryCode);
// System.err.println("NumberParseException was thrown:>>>>>>>>>>>> " + pNumberProto);
boolean isValid = phoneUtil.isValidNumber(pNumberProto);
if(isValid){
System.out.println(phoneUtil.format(pNumberProto, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL));
phoneVerfid = phoneUtil.format(pNumberProto, PhoneNumberUtil.PhoneNumberFormat.E164);
}
} catch (NumberParseException e) {
// System.err.println("NumberParseException was thrown: " + e.toString() +" ???" +phone.getString(contactNumberColumnIndex) + countryCode);
}
///////////////////////////////
phoneNumber2 = phoneVerfid + "_";
// output.append("\n Phone number:" + phoneNumber2);
phoneC = phoneC + phoneNumber2;
// System.out.println("Country = "+countryCode(phoneNumber2) + " p= " +phoneNumber2);
phone.moveToNext();
}
}
phone.close();
/////////////////////////////////////////////////////////////
// Read every email id associated with the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null);
emailC = "";
email = "";
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA)) + "%";
if (!emailC.contains(email)) {
emailC = emailC + email;
// output.append("\n Email:" + email);
}
}
emailCursor.close();
//////////// Adresss//////
String postalData = "";
String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] addrWhereParams = new String[]{String.valueOf(contact_id), ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
Cursor addrCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, addrWhere, addrWhereParams, null);
if (addrCur.moveToFirst()) {
postalData = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
//output.append("\n Address:" + postalData);
adressC = adressC + " " + postalData;
}
addrCur.close();
}
if (phoneC != "") {
if (bitmap != null) {
Bitmap bitmap1 = getResizedBitmap(bitmap,210);
image = getStringImage(bitmap1);
if(bitmap1!=null) {
bitmap1.recycle();
}
// System.out.println("KKKKKKKKKKKKKKKKKKK >>>>>>>>> "+image);
}
Contact_Details dt = new Contact_Details(name, phoneC, UIDD, country_code, image, emailC, adressC);
dataArray.add(dt);
if(bitmap!=null){ bitmap.recycle();}
image = "";
}
}
submit1User2Contacs();
}
}
MainAcivity onCreate Method :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new MyTask().execute();}
Looks like you haven't called close method for cursor object.
Calling cursor.close() will solve your problem
i try below code instead of new MyTask().execute() class. and the below code work for me. i also try below code with xxx.run(); method instead of start();. run() method also not work. only thread with xxx.start(); worked. so the correct code is below one. Thanks every one.
new Thread(new Runnable(){
#Override
public void run() {
//my method
checkUser();
}
}).start();

ListView not showing anything

My ListView is not showing anything.
I'm downloading the top stories API from Hacker-News and putting them in my app. I want to put the titles of those stories in my list view (they are over 100).
I download them and store them in a database for permanent storage and then add them to my list view, but NOTHING is showing up in my app. Can anyone explain to me why?
UPDATE: I get a CursorIndexOutOfBoundException problem. ( index 350 out of 350)
public class MainActivity extends AppCompatActivity {
ListView listView;
private SQLiteDatabase myDatabase;
private Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
DownloadIDs ids = new DownloadIDs();
String URL = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty";
ids.execute(URL);
try {
ArrayList<String> titles = new ArrayList<String>();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, titles);
listView.setAdapter(arrayAdapter);
myDatabase = this.openOrCreateDatabase("HackerNews", MODE_PRIVATE, null);
Cursor cursor1 = myDatabase.rawQuery("SELECT * FROM ids", null);
int index = cursor1.getColumnIndex("urlID");
cursor1.moveToFirst();
while (cursor1 != null) {
String newUrl = "https://hacker-news.firebaseio.com/v0/item/" + cursor1.getString(index) + ".json?print=pretty";
new DownloadContent().execute(newUrl);
cursor1.moveToNext();
}
Cursor cursor2 = myDatabase.rawQuery("SELECT * FROM content", null);
int titleIndex = cursor2.getColumnIndex("title");
cursor2.moveToFirst();
titles.add("Hello");
while(cursor2 != null){
titles.add(cursor2.getString(titleIndex));
arrayAdapter.notifyDataSetChanged();
cursor2.moveToNext();
}
}catch (Exception e){
e.printStackTrace();
}
}
public class DownloadIDs extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data >= 0) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS ids (id INTEGER PRIMARY KEY, urlID VARCHAR)");
cursor = myDatabase.rawQuery("SELECT COUNT(*) FROM ids", null);
cursor.moveToFirst();
int count = cursor.getInt(0);
if (!(count > 0)) {
JSONArray ids = new JSONArray(s);
for (int i = 0; i < ids.length(); i++) {
myDatabase.execSQL("INSERT INTO ids (urlID) VALUES ('" + ids.getString(i) + "')");
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}
public class DownloadContent extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data >= 0) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS content(id INTEGER PRIMARY KEY, title VARCHAR, url VARCHAR)");
cursor = myDatabase.rawQuery("SELECT COUNT(*) FROM content", null);
cursor.moveToFirst();
int count = cursor.getInt(0);
if (!(count > 0)) {
JSONObject jsonObject = new JSONObject(s);
String title = jsonObject.getString("title");
Log.i("title", title);
String url = jsonObject.getString("url");
Log.i("url", url);
myDatabase.execSQL("INSERT INTO content (title, url) VALUES('" + title + "','" + url + "')");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
}
Got it! I fixed it. I just had to reduce the amount of news (I decided to choose the top 20 ones), and I decided to run only one ASyncTask on my app.
Here is the edited code:
PD: Thanks to #cafebabe1991 as he gave me tips on how to fix it. Thanks!
public class MainActivity extends AppCompatActivity {
ListView listView;
private SQLiteDatabase myDatabase;
ArrayList<String> titles;
ArrayList<String> urls;
ArrayAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
titles = new ArrayList<>();
urls = new ArrayList<>();
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, titles);
listView.setAdapter(arrayAdapter);
try {
myDatabase = this.openOrCreateDatabase("HackerNews", MODE_PRIVATE, null);
DownloadTask downloadTask = new DownloadTask();
String URL = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty";
downloadTask.execute(URL);
Cursor cursor = myDatabase.rawQuery("SELECT * FROM content", null);
int titleIndex = cursor.getColumnIndex("title");
int urlIndex = cursor.getColumnIndex("url");
cursor.moveToFirst();
while(cursor!=null){
titles.add(cursor.getString(titleIndex));
urls.add(cursor.getString(urlIndex));
cursor.moveToNext();
}
arrayAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), MainActivity2.class);
MainActivity2.url = urls.get(position);
startActivity(intent);
}
});
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String articleInfo = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data >= 0) {
char current = (char) data;
articleInfo += current;
data = reader.read();
}
//myDatabase.execSQL("CREATE TABLE IF NOT EXISTS ids (id INTEGER PRIMARY KEY, urlID VARCHAR)");
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS content (id INTEGER PRIMARY KEY, title VARCHAR, url VARCHAR)");
myDatabase.delete("content", null, null);
JSONArray ids = new JSONArray(articleInfo);
for (int i = 0; i < 20; i++) {
//myDatabase.execSQL("INSERT INTO ids (urlID) VALUES ('" + ids.getString(i) + "')");
String articleInfo2 = "";
URL url2 = new URL("https://hacker-news.firebaseio.com/v0/item/" + ids.getString(i) + ".json?print=pretty");
HttpURLConnection urlConnection2 = (HttpURLConnection) url2.openConnection();
InputStream inputStream2 = urlConnection2.getInputStream();
InputStreamReader reader2 = new InputStreamReader(inputStream2);
int data2 = reader2.read();
while (data2 >= 0) {
char current2 = (char) data2;
articleInfo2 += current2;
data2 = reader2.read();
}
JSONObject jsonObject = new JSONObject(articleInfo2);
String title = "'" + jsonObject.getString("title").replaceAll("'", "") + "'";
String articleURL = "'" + jsonObject.getString("url") + "'";
myDatabase.execSQL("INSERT INTO content (title, url) VALUES (" + title + "," + articleURL + ")");
}
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
}
The problem lies in this code
1.)
Cursor cursor1 = myDatabase.rawQuery("SELECT * FROM ids", null);
int index = cursor1.getColumnIndex("urlID");
cursor1.moveToFirst();
while (cursor1 != null) {
String newUrl = "https://hacker-news.firebaseio.com/v0/item/" + cursor1.getString(index) + ".json?print=pretty";
new DownloadContent().execute(newUrl);
cursor1.moveToNext();
}
How ?
You say to to cursor to get you the column index and from that you fetch the item id, but when database is empty the value will be null. Hence the api will not return a response. Additionally you do the same mistake with the cursor as mentioned in the point below.
2.)
int titleIndex = cursor2.getColumnIndex("title");
cursor2.moveToFirst();
titles.add("Hello");
while(cursor2 != null){
titles.add(cursor2.getString(titleIndex));
arrayAdapter.notifyDataSetChanged();
cursor2.moveToNext();
}
How ?
You said to the cursor to move to the first record (moveToFirst()) , what if the currently no record exist. This method returns false if the cursor is empty. So make sure that this method returns true and then proceed.
OR
Do this(Better approach)...
while(cursor.moveToNext()) {
//If inside , that means you are on the next record.Fetch the column values here
}
References :
Cursor methods
Discussion about best ways to iterate a cursor
For loading data into the listview from the database

Load different values from a database column

How I can get a different values from a column with the same name (like the photo)?
In the photo, "test" have a 3 differents values, how I can load them to a ListView or a Spinner?
I have this code, works, but don't get the 3 values, only first value:
MainActivity
public void lookupProduct (View view) {
DatabaseHandler dbHandler = new DatabaseHandler(getApplicationContext());
Name name = dbHandler.findProduct(spinner.getSelectedItem().toString());
Toast.makeText(this, spinner.getSelectedItem().toString(), Toast.LENGTH_LONG).show();
Intent j = new Intent(view.getContext(), SubActivity.class);
Bundle dados = new Bundle();
if (name != null) {
inputLabel.setText(String.valueOf(name.getName()));
values.setText(String.valueOf(name.getValue()));
// Passar para SubActivity
dados.putString("name", String.valueOf(name.getName()));
dados.putString("value", String.valueOf(name.getValue()));
} else {
inputLabel.setText("No Match Found");
dados.putString("name","No Match Found" );
dados.putString("value", "No Match Found");
}
j.putExtras(dados);
startActivity(j);
}
DatabaseHelper
public Name findProduct(String name) {
String query = "Select * FROM " + TABLE_LABELS + " WHERE " + KEY_NAME + " = \"" + name + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Name names = new Name();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
names.setID(Integer.parseInt(cursor.getString(0)));
names.setName(cursor.getString(1));
names.setValue(cursor.getString(2));
cursor.close();
} else {
names = null;
}
db.close();
return names;
}
NameClass
public class Name {
private int _id;
private String _name;
private String _value;
public Name() {
}
public Name(int id, String name, String value) {
this._id = id;
this._name = name;
this._value = value;
}
public Name(String name, String value) {
this._name = name;
this._value = value;
}public String getName() {
return this._name;
}
public String getValue() {
return this._value;
}
Try this
Name names = new Name();
ArrayList<Name > listaName= new ArrayList<>();//create an arraylist of your
custom objects
if (cursor.moveToFirst()) {
do {
names.setID(Integer.parseInt(cursor.getString(0)));
names.setName(cursor.getString(1));
names.setValue(cursor.getString(2));
listaName.add(names);//add your object to arraylist(you were overriding the object.)
} while (cursor.moveToNext());
cursor.close();
//AND ALSO CLOSE DB:
db.close
EDIT 2: Try this and change your --> String Query = "Select * from "+TABLE_NAME;
for ( int i= 1; i< listaName.size(); i++ ) {
System.out.println(listaName.get(i).getName());
}
Your problem:
public Name findProduct(String name) {
String query = "Select * FROM " + TABLE_LABELS + " WHERE " + KEY_NAME + " = \"" + name + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Name names = new Name();
if (cursor.moveToFirst()) {
cursor.moveToFirst(); // this is not necessary because on the top line,
you put it in that position
names.setID(Integer.parseInt(cursor.getString(0)));
names.setName(cursor.getString(1));
names.setValue(cursor.getString(2));
cursor.close(); // You should not close until it is
completely used
} else {
names = null;
}
db.close();
return names;
}
And to read all the cursor is necessary to use a do-while method
If you have any problems, you can ask me again
Though not yet tested, you can try this:
// fetch data from DB
public ArrayList<Name> findProduct(String name) {
String query = "Select * FROM " + TABLE_LABELS + " WHERE " + KEY_NAME + " = \"" + name + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
ArrayList<Name> listOfNames= new ArrayList<>();
if (cursor.moveToFirst()) {
do {
listOfNames.add(new Name(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2)));
} while (cursor.moveToNext());
cursor.close();
db.close
return listOfNames;
}
// add data on spinner
public void addItemsOnSpinner() {
Spinner mSpinner = (Spinner) findViewById(R.id.mSpinner);
ArrayList<String> list = new ArrayList<String>();
for(Name name: findProduct("test")){
list.add(name.getValue());
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(dataAdapter);
}

Database is not retrieving all rows instead getting only unique rows

I am working on a code snippet where i am storing my json encoded data into a txt file,and using following method to separate all parts and adding them into database.
public boolean addAnswersFromJSONArray() {
boolean flag = false;
Answer answer = new Answer();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "user_live.txt");
FileReader fr;
JsonReader reader;
try {
fr = new FileReader(file);
reader = new JsonReader(fr);
reader.beginArray();
reader.setLenient(true);
while (reader.hasNext()) {
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("product_name")) {
answer.setProductName(reader.nextString());
} else if (name.equals("subject")) {
answer.setSubject(reader.nextString());
} else if (name.equals("month")) {
answer.setMonth(reader.nextString());
} else if (name.equals("year")) {
answer.setYear(reader.nextString());
} else if (name.equals("question")) {
answer.setQuestion(reader.nextString());
} else if (name.equals("answer")) {
answer.setAnswer(reader.nextString());
} else if (name.equals("question_no")) {
answer.setQuestion_no(reader.nextString());
} else if (name.equals("marks")) {
answer.setMarks(reader.nextString());
} else {
reader.skipValue();
}
}
answer.save(db);
reader.endObject();
flag = true;
}
reader.endArray();
reader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
file.delete();
db.close();
}
return flag;
}
and then i am retrieving each fields departments,subjects,month and year,questions,answers,question_no, but while retrieving marks i am getting only unique entries that is 10 and 5....Ideally the size of one set is 18 so i m getting ArrayIndexoutOfBounds Exception.
//database calling part
marks = db.getMarksList(department, subject, month_year);
database method is,
public String[] getMarksList(String department, String subject,
String month_year) {
String month = month_year.split("-")[0];
String year = month_year.split("-")[1];
String whereClause = DEPARTMENT + " = '" + department + "'" + " AND "
+ SUBJECT + " = '" + subject + "' AND " + MONTH + " = '"
+ month + "' AND " + YEAR + " = '" + year + "'";
System.out.println("questions: " + whereClause);
Cursor cursor = db.query(true, "ANSWERS", new String[] { "MARKS" },
whereClause, null, null, null, "DEPARTMENT", null);
String list[] = new String[cursor.getCount()];
int i = 0;
if (cursor != null && cursor.getCount() > 0) {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
.moveToNext()) {
list[i] = new String(cursor.getString(0));
i++;
}
}
return list;
}
Can anyone help me to resolve this issue?? Why getting only unique value,I have checked my json result also each row contains marks.
i got the solution for this,
Changed database query and method as following,
public List<Answer> getMarksList(String department, String subject,
String month_year) {
List<Answer> list = new ArrayList<Answer>();
String month = month_year.split("-")[0];
String year = month_year.split("-")[1];
try {
String sql1 = "select all marks from " + TABLE_NAME
+ " where department = '" + department
+ "' AND subject = '" + subject + "' AND month = '" + month
+ "' AND year = '" + year + "';";
SQLiteDatabase db1 = this.getWritableDatabase();
Cursor cursor = db1.rawQuery(sql1, null);
if (cursor.moveToFirst()) {
do {
Answer a = new Answer();
a.setMarks(cursor.getString(0));
list.add(a);
} while (cursor.moveToNext());
}
} catch (Exception e) {
}
return list;
}
using "all" in query is retrieving all records.

Categories

Resources