Expert Please advise with following my query.
I am trying to run the query in Android studio .
As is : Spinner shows the X value as per edittext X value input using Textwatcher.
To be : Spinner should show the Y value as per X value input in Edit text.
Example: If i enter value "6" in edittext then my spinner should show the vaue "Data Structures"
My Database follows.
Database follows
package com.bar.example.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
class DBHelper extends SQLiteOpenHelper {
private Context mContext;
//TASK: DEFINE THE DATABASE VERSION AND NAME (DATABASE CONTAINS MULTIPLE TABLES)
static final String DATABASE_NAME = "OCC";
private static final int DATABASE_VERSION = 1;
//TASK: DEFINE THE FIELDS (COLUMN NAMES) FOR THE COURSES TABLE
public static final String COURSES_TABLE = "Courses";
public static final String COURSES_KEY_FIELD_ID = "_id";
public static final String FIELD_ALPHA = "alpha";
public static final String FIELD_NUMBER = "number";
public static final String FIELD_TITLE = "title";
//TASK: DEFINE THE FIELDS (COLUMN NAMES) FOR THE INSTRUCTORS TABLE
//TASK: DEFINE THE FIELDS (COLUMN NAMES) FOR THE OFFERINGS TABLE
private static final String OFFERINGS_TABLE = "Offerings";
private static final String OFFERINGS_KEY_FIELD_ID = "crn";
private static final String FIELD_SEMESTER_CODE = "semester_code";
public static final String FIELD_COURSE_ID = "course_id";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext = context;
}
#Override
public void onCreate(SQLiteDatabase database) {
String createQuery = "CREATE TABLE " + COURSES_TABLE + "(" +
COURSES_KEY_FIELD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
FIELD_ALPHA + " TEXT, " +
FIELD_NUMBER + " TEXT, " +
FIELD_TITLE + " TEXT" + ")";
database.execSQL(createQuery);
createQuery = "CREATE TABLE " + OFFERINGS_TABLE + "(" +
OFFERINGS_KEY_FIELD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
FIELD_SEMESTER_CODE + " INTEGER, " +
FIELD_COURSE_ID + " INTEGER, "
+
"FOREIGN KEY(" + FIELD_COURSE_ID + ") REFERENCES "
+
COURSES_TABLE + "(" + COURSES_KEY_FIELD_ID + ")" +
")";
database.execSQL(createQuery);
}
#Override
public void onUpgrade(SQLiteDatabase database,
int oldVersion,
int newVersion) {
database.execSQL("DROP TABLE IF EXISTS " + COURSES_TABLE);
database.execSQL("DROP TABLE IF EXISTS " + OFFERINGS_TABLE);
onCreate(database);
}
//********** COURSE TABLE OPERATIONS: ADD, GETALL, EDIT, DELETE
public void addCourse(Course course) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_ALPHA, course.getAlpha());
values.put(FIELD_NUMBER, course.getNumber());
values.put(FIELD_TITLE, course.getTitle());
db.insert(COURSES_TABLE, null, values);
// CLOSE THE DATABASE CONNECTION
db.close();
}
public ArrayList < Course > getAllCourses() {
ArrayList < Course > coursesList = new ArrayList < > ();
SQLiteDatabase database = this.getReadableDatabase();
//Cursor cursor = database.rawQuery(queryList, null);
Cursor cursor = database.query(
COURSES_TABLE,
new String[] {
COURSES_KEY_FIELD_ID,
FIELD_ALPHA,
FIELD_NUMBER,
FIELD_TITLE
},
null,
null,
null, null, null, null);
//COLLECT EACH ROW IN THE TABLE
if (cursor.moveToFirst()) {
do {
Course course =
new Course(cursor.getInt(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3));
coursesList.add(course);
} while (cursor.moveToNext());
}
return coursesList;
}
public void deleteCourse(Course course) {
SQLiteDatabase db = this.getWritableDatabase();
// DELETE THE TABLE ROW
db.delete(COURSES_TABLE, COURSES_KEY_FIELD_ID + " = ?",
new String[] {
String.valueOf(course.getId())
});
db.close();
}
public void deleteAllCourses() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(COURSES_TABLE, null, null);
db.close();
}
public void updateCourse(Course course) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_ALPHA, course.getAlpha());
values.put(FIELD_NUMBER, course.getNumber());
values.put(FIELD_TITLE, course.getTitle());
db.update(COURSES_TABLE, values, COURSES_KEY_FIELD_ID + " = ?",
new String[] {
String.valueOf(course.getId())
});
db.close();
}
public Course getCourse(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
COURSES_TABLE,
new String[] {
COURSES_KEY_FIELD_ID,
FIELD_ALPHA,
FIELD_NUMBER,
FIELD_TITLE
},
COURSES_KEY_FIELD_ID + "=?",
new String[] {
String.valueOf(id)
},
null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Course course = new Course(
cursor.getInt(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3));
db.close();
return course;
}
//********** OFFERING TABLE OPERATIONS: ADD, GETALL, EDIT, DELETE
public void addOffering(int crn, int semesterCode, int courseId) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(OFFERINGS_KEY_FIELD_ID, crn);
values.put(FIELD_SEMESTER_CODE, semesterCode);
values.put(FIELD_COURSE_ID, courseId);
db.insert(OFFERINGS_TABLE, null, values);
// CLOSE THE DATABASE CONNECTION
db.close();
}
public ArrayList < Offering > getAllOfferings() {
ArrayList < Offering > offeringsList = new ArrayList < > ();
SQLiteDatabase database = this.getReadableDatabase();
//Cursor cursor = database.rawQuery(queryList, null);
Cursor cursor = database.query(
OFFERINGS_TABLE,
new String[] {
OFFERINGS_KEY_FIELD_ID,
FIELD_SEMESTER_CODE,
FIELD_COURSE_ID
},
null,
null,
null, null, null, null);
//COLLECT EACH ROW IN THE TABLE
if (cursor.moveToFirst()) {
do {
Course course = getCourse(cursor.getInt(2));
//Instructor instructor = getInstructor(cursor.getInt(3));
Offering offering = new Offering(cursor.getInt(0),
cursor.getInt(1), course);
offeringsList.add(offering);
} while (cursor.moveToNext());
}
return offeringsList;
}
public void deleteOffering(Offering offering) {
SQLiteDatabase db = this.getWritableDatabase();
// DELETE THE TABLE ROW
db.delete(OFFERINGS_TABLE, OFFERINGS_KEY_FIELD_ID + " = ?",
new String[] {
String.valueOf(offering.getCRN())
});
db.close();
}
public void deleteAllOfferings() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(OFFERINGS_TABLE, null, null);
db.close();
}
public void updateOffering(Offering offering) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_SEMESTER_CODE, offering.getSemesterCode());
values.put(FIELD_COURSE_ID, offering.getCourse().getId());
db.update(OFFERINGS_TABLE, values, OFFERINGS_KEY_FIELD_ID + " = ?",
new String[] {
String.valueOf(offering.getCRN())
});
db.close();
}
public Offering getOffering(int crn) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
OFFERINGS_TABLE,
new String[] {
OFFERINGS_KEY_FIELD_ID,
FIELD_SEMESTER_CODE,
FIELD_COURSE_ID
},
OFFERINGS_KEY_FIELD_ID + "=?",
new String[] {
String.valueOf(crn)
},
null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Course course = getCourse(cursor.getInt(2));
//Instructor instructor = getInstructor(cursor.getInt(3));
Offering offering = new Offering(cursor.getInt(0),
cursor.getInt(1), course);
db.close();
return offering;
}
public Cursor getAllLabelsAsCursor() {
String[] columns = new String[] {
"rowid AS _id, *"
}; // Need _id column for SimpleCursorAdapter
return this.getWritableDatabase().query(COURSES_TABLE, columns, null, null, null, null, null);
}
public boolean importCoursesFromCSV(String csvFileName) {
AssetManager manager = mContext.getAssets();
InputStream inStream;
try {
inStream = manager.open(csvFileName);
} catch (IOException e) {
e.printStackTrace();
return false;
}
BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream));
String line;
try {
while ((line = buffer.readLine()) != null) {
String[] fields = line.split(",");
if (fields.length != 4) {
Log.d("OCC Course Finder", "Skipping Bad CSV Row: " + Arrays.toString(fields));
continue;
}
int id = Integer.parseInt(fields[0].trim());
String alpha = fields[1].trim();
String number = fields[2].trim();
String title = fields[3].trim();
addCourse(new Course(id, alpha, number, title));
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean importOfferingsFromCSV(String csvFileName) {
AssetManager am = mContext.getAssets();
InputStream inStream = null;
try {
inStream = am.open(csvFileName);
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream));
String line;
try {
while ((line = buffer.readLine()) != null) {
String[] fields = line.split(",");
if (fields.length != 4) {
Log.d("OCC Course Finder", "Skipping Bad CSV Row: " + Arrays.toString(fields));
continue;
}
int crn = Integer.parseInt(fields[0].trim());
int semesterCode = Integer.parseInt(fields[1].trim());
int courseId = Integer.parseInt(fields[2].trim());
addOffering(crn, semesterCode, courseId);
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}
main activity.
package com.bar.example.myapplication;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class CourseSearchActivity extends AppCompatActivity {
private DBHelper db;
private List < Course > allCoursesList;
private List < Offering > allOfferingsList;
private List < Offering > filteredOfferingsList;
public Button reset;
private EditText courseTitleEditText;
private Spinner ok;
private ListView offeringsListView;
// private selectedInstructorName selectedInstructorName;
private InstructorSpinnerAdapter instructorSpinnerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_search);
deleteDatabase(DBHelper.DATABASE_NAME);
db = new DBHelper(this);
db.importCoursesFromCSV("courses.csv");
db.importOfferingsFromCSV("offerings.csv");
Button reset = (Button) findViewById(R.id.resetButton);
allOfferingsList = db.getAllOfferings();
filteredOfferingsList = new ArrayList < > (allOfferingsList);
allCoursesList = db.getAllCourses();
courseTitleEditText = (EditText) findViewById(R.id.courseTitleEditText);
courseTitleEditText.addTextChangedListener(courseTitleTextWatcher);
ok = (Spinner) findViewById(R.id.spinner1);
// offeringListAdapter = new OfferingListAdapter(this, R.layout.offering_list_item, filteredOfferingsList);
// ok.setAdapter(offeringListAdapter);
instructorSpinnerAdapter = new InstructorSpinnerAdapter(this, R.layout.offering_list_item, filteredOfferingsList);
ArrayAdapter < String > instructorSpinnerAdapter = new ArrayAdapter < String >
(this, android.R.layout.simple_spinner_item, getAllCourse());
ok.setAdapter(instructorSpinnerAdapter);
ok.setOnItemSelectedListener(instructorSpinnerListener);
}
private String[] getAllCourse1() {
String[] instructorNames = new String[allCoursesList.size() + 1];
instructorNames[0] = "[Select Course]";
for (int i = 1; i < instructorNames.length; i++) {
instructorNames[i] = allCoursesList.get(i - 1).getTitle();
}
return instructorNames;
}
private ArrayList < String > getAllCourse() {
ArrayList < String > instructorNames = new ArrayList < > ();
instructorNames.add("[Select Course]");
for (int i = 0; i < allCoursesList.size(); i++) {
instructorNames.add(allCoursesList.get(i).getTitle());
}
return instructorNames;
}
public TextWatcher courseTitleTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String input = charSequence.toString().toLowerCase();
ArrayAdapter adapter = (ArrayAdapter) ok.getAdapter();
adapter.clear();
if (input.equals("")) {
adapter.addAll(getAllCourse());
} else {
Course course;
for (int j = 0; j < allCoursesList.size(); j++) {
// If the course title starts with the user input,
// add it to the listAdapter
course = allCoursesList.get(j);
if (course.getTitle().toLowerCase().startsWith(input)) {
adapter.add(course.getTitle());
}
}
}
adapter.notifyDataSetChanged();
if (adapter.getCount() != 0) ok.setSelection(0);
}
#Override
public void afterTextChanged(Editable editable) {
}
};
public AdapterView.OnItemSelectedListener instructorSpinnerListener = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView << ? > adapterView, View view, int i, long l) {
String selectedInstructorName = adapterView.getItemAtPosition(i).toString();
if (selectedInstructorName.equals("[Select Instructor]")) {
instructorSpinnerAdapter.clear();
for (Offering offering: allOfferingsList)
instructorSpinnerAdapter.add(offering);
} else {
instructorSpinnerAdapter.clear();
}
}
#Override
public void onNothingSelected(AdapterView << ? > adapterView) {
adapterView.setSelection(0);
// Toast.makeText(getApplicationContext(), "Why?", Toast.LENGTH_SHORT).show();
}
};
}
Activity_course_search.xml
<< ? xml version = "1.0"
encoding = "utf-8" ? >
<
LinearLayout
xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android: id = "#+id/activity_course_search"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: orientation = "vertical"
android: paddingBottom = "#dimen/activity_vertical_margin"
android: paddingLeft = "#dimen/activity_horizontal_margin"
android: paddingRight = "#dimen/activity_horizontal_margin"
android: paddingTop = "#dimen/activity_vertical_margin"
tools: context = "com.bar.example.myapplication.CourseSearchActivity" >
<
LinearLayout
android: orientation = "horizontal"
android: layout_width = "match_parent"
android: layout_height = "wrap_content" >
<
TextView
android: text = "Filter By Instructor"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: id = "#+id/textView" /
>
<
Spinner
android: id = "#+id/instructorSpinner"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_weight = "1" / >
<
/LinearLayout>
<
LinearLayout
android: orientation = "horizontal"
android: layout_width = "match_parent"
android: layout_height = "wrap_content" >
<
TextView
android: text = "Filter By Course Title"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: id = "#+id/textView2" /
>
<
EditText
android: id = "#+id/courseTitleEditText"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: inputType = "textPersonName"
android: ems = "10" /
>
<
/LinearLayout>
<
LinearLayout
android: orientation = "horizontal"
android: layout_width = "match_parent"
android: layout_height = "wrap_content" >
<
Button
android: text = "#string/reset_button_text"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_weight = "1"
android: id = "#+id/resetButton" /
>
<
/LinearLayout>
<
ListView
android: id = "#+id/offeringsListView"
android: layout_width = "match_parent"
android: layout_height = "18dp" >
<
/ListView>
<
Spinner
android: id = "#+id/spinner1"
android: layout_width = "341dp"
android: layout_height = "93dp"
android: layout_weight = "1" / >
<
/LinearLayout>
offering_list_item.xml
<< ? xml version = "1.0"
encoding = "utf-8" ? >
<
LinearLayout xmlns : android = "http://schemas.android.com/apk/res/android"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: id = "#+id/offeringListLinearLayout" >
<
LinearLayout
android: orientation = "vertical"
android: layout_width = "match_parent"
android: layout_height = "match_parent" >
<
TextView
android: text = "TextView"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: textSize = "20sp"
android: id = "#+id/offeringListFullNameTextView" / >
<
/LinearLayout>
<
/LinearLayout>
Main Screen 1 :
Requirement 1 : (Working Fine) spinner selection from database.
Requirement 2 : Working but need in another way . Spinner display from database based on edittext entry using textwacher. What i want is that if enter "Number A170 then my spinner should show "title" Java Programming 1 from database
Current screen shows
I want it in this way ...
revised onTextChanged code.
public TextWatcher courseTitleTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String input = charSequence.toString().toLowerCase();
ArrayAdapter adapter = (ArrayAdapter) ok.getAdapter();
adapter.clear();
if (input.equals("")) {
adapter.addAll(getAllCourse());
} else {
Course course;
for (int j = 0; j < CoursesList.size(); j++) {
// If the course title starts with the user input,
// add it to the listAdapter
// course = allCoursesList.get(j);
if (courseTitleEditText.getText().equals(CoursesList.get(j).get("number"))) {
//adapter.add(course.getTitle());
ok.setSelection(j);
}
}
}
// adapter.notifyDataSetChanged();
//if(adapter.getCount() != 0)
// ok.setSelection(i);
}
#Override
public void afterTextChanged(Editable editable) {
}
};
Try this. It should solve your issue.
Replace if (course.getTitle().toLowerCase().startsWith(input)) {
with if (course.getNumber().toLowerCase().startsWith(input)) {.
i think i figure what do you need
actully it's little simple
im try to work it with your code but not by modeling way like you
it will be by hashmap array
first we need to get the data from you sqlite by using this code
THIS in class DBHelper
import java.util.HashMap;
import java.util.Map;
this the import you need here
public ArrayList<Map<String, String>> getCourses()
{
ArrayList<Map<String, String>> array_list = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from " + COURSES_TABLE, null);
res.moveToFirst();
while(res.isAfterLast() == false){
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("id", res.getString(res.getColumnIndex(COURSES_KEY_FIELD_ID)));
datanum.put("alpha", res.getString(res.getColumnIndex(FIELD_ALPHA)));
datanum.put("number", res.getString(res.getColumnIndex(FIELD_NUMBER)));
datanum.put("title", res.getString(res.getColumnIndex(FIELD_TITLE)));
array_list.add(datanum);
res.moveToNext();
}
return array_list;
}
this code here will work perfect with you not need to edit i make it with your class
now you need to call this method in you class
THIS in class CourseSearchActivity
DBHelper DB;
ArrayList<Map<String, String>> CoursesList = new ArrayList<Map<String, String>>();
on create
DB = new DBHelper(this);
CoursesList= DB.getCourses();
now you have all in your CoursesList now you need to figure out which spinner position you wanna to select it
so
you going to loop on it
THIS in Textlistener
for(int i = 0 ; i < CoursesList.size() ; i++){
if(courseTitleEditText.getText().equals(CoursesList.get(i).get("number"))){//ex.A170
// you must to be filled your spinner from same courses db and here you gonna to set your selection by iteration
ok.setSelection(i);
}
}
maybe it's not the right thing to your code because i see you use modeling in your code and i use Hashmap but i think it's useful to see the same way in your modeling from this code
i didn't test it i wrote it direct so test and told me what happen
hope i help
Related
I use SQLite database for my app and i want to save data from multiple activities into one table. in the first activity i use the add method to create a row in the table. In the next activity i use update method to update the columns in the existing row.
I use DB Browser for SQLite app to check my database and it shows datas i saved from second activity are not in database (Null). I don't know what's the problem.
Here are my classes :
SQLiteHelper :
public class SQLiteHelper extends SQLiteOpenHelper implements ProjectDAO {
public SQLiteHelper(Context context) {
super(context, "my_db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("CREATE TABLE tbl_project_info (id INTEGER PRIMARY KEY," +
"name TEXT," +
"company_name TEXT," +
"address TEXT," +
"length1 TEXT," +
"length2 TEXT," +
"length3 TEXT," +
"length4 TEXT," +
"length5 TEXT," +
"diameter1 Text,"+
"diameter2 Text,"+
"diameter3 Text,"+
"diameter4 Text,"+
"diameter5 Text)");
} catch (SQLiteException e) {
Log.e("SQLITE", "onCreate: " + e.toString());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
#Override
public boolean addProject(Project project) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", project.getName());
contentValues.put("company_name", project.getCompany_name());
contentValues.put("address", project.getAddress());
contentValues.put("length1",project.getLength1());
contentValues.put("length2",project.getLength2());
contentValues.put("length3",project.getLength3());
contentValues.put("length4",project.getLength4());
contentValues.put("length5",project.getLength5());
contentValues.put("diameter1",project.getDiameter1());
contentValues.put("diameter2",project.getDiameter2());
contentValues.put("diameter3",project.getDiameter3());
contentValues.put("diameter4",project.getDiameter4());
contentValues.put("diameter5",project.getDiameter5());
long result = db.insert("tbl_project_info", null, contentValues);
db.close();
return result != -1;
}
#Override
public int getProjectsCount() {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM tbl_project_info", null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
}
#Override
public boolean updateProject(Project project) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("length1",project.getLength1());
contentValues.put("length2",project.getLength2());
contentValues.put("length3",project.getLength3());
contentValues.put("length4",project.getLength4());
contentValues.put("length5",project.getLength5());
contentValues.put("diameter1",project.getDiameter1());
contentValues.put("diameter2",project.getDiameter2());
contentValues.put("diameter3",project.getDiameter3());
contentValues.put("diameter4",project.getDiameter4());
contentValues.put("diameter5",project.getDiameter5());
db.update("tbl_project_info",contentValues,"id = ?", new String[]{String.valueOf(project.getId())});
db.close();
return true;
}
#Override
public List<Project> getAllProjects() {
List<Project> projects = new ArrayList<>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM tbl_project_info", null);
if (cursor.moveToFirst()) {
do {
Project project = new Project();
project.setName(cursor.getString(0));
project.setCompany_name(cursor.getString(1));
project.setAddress(cursor.getString(2));
projects.add(project);
} while (cursor.moveToNext());
}
return projects;
}
}
NewProjectActivity :
public class NewProjectActivity extends AppCompatActivity {
private ProjectDAO projectDAO;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_project);
projectDAO = DBInjector.provideProjectDao(this);
setupViews();
}
private void setupViews() {
final EditText projectNameET = findViewById(R.id.et_newProject_projectName);
final EditText companyNameET = findViewById(R.id.et_newProject_companyName);
final EditText addressET = findViewById(R.id.et_newProject_address);
Button saveInfoBTN = findViewById(R.id.btn_newProject_saveInfo);
saveInfoBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (projectNameET.length() > 0) {
if (companyNameET.length() > 0) {
if (addressET.length() > 0) {
Project project = new Project();
project.setName(projectNameET.getText().toString());
project.setCompany_name(companyNameET.getText().toString());
project.setAddress(addressET.getText().toString());
if (projectDAO.addProject(project)){
Toast.makeText(NewProjectActivity.this, "Success", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(NewProjectActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
}
}
Intent intent = new Intent(NewProjectActivity.this,MainActivity.class);
startActivity(intent);
}
});
}
}
MainActivity :
public class MainActivity extends AppCompatActivity {
private ProjectDAO projectDAO;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
projectDAO = DBInjector.provideProjectDao(this);
final EditText lengthET1 = findViewById(R.id.et_main_length1);
final EditText lengthET2 = findViewById(R.id.et_main_length2);
final EditText lengthET3 = findViewById(R.id.et_main_length3);
final EditText lengthET4 = findViewById(R.id.et_main_length4);
final EditText lengthET5 = findViewById(R.id.et_main_length5);
final EditText diameterET1 = findViewById(R.id.et_main_diameter1);
final EditText diameterET2 = findViewById(R.id.et_main_diameter2);
final EditText diameterET3 = findViewById(R.id.et_main_diameter3);
final EditText diameterET4 = findViewById(R.id.et_main_diameter4);
final EditText diameterET5 = findViewById(R.id.et_main_diameter5);
Button calculateButton = findViewById(R.id.btn_main_calculate);
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
float Le1 = 0;
if (lengthET1.length() > 0) {
String L1 = lengthET1.getText().toString();
Le1 = Float.parseFloat(L1);
}
float Di1 = 0;
if (diameterET1.length() > 0) {
String D1 = diameterET1.getText().toString();
Di1 = Float.parseFloat(D1);
}
float Le2 = 0;
if (lengthET2.length() > 0) {
String L2 = lengthET2.getText().toString();
Le2 = Float.parseFloat(L2);
}
float Di2 = 0;
if (diameterET2.length() > 0) {
String D2 = diameterET2.getText().toString();
Di2 = Float.parseFloat(D2);
}
float Le3 = 0;
if (lengthET3.length() > 0) {
String L3 = lengthET3.getText().toString();
Le3 = Float.parseFloat(L3);
}
float Di3 = 0;
if (diameterET3.length() > 0) {
String D3 = diameterET3.getText().toString();
Di3 = Float.parseFloat(D3);
}
float Le4 = 0;
if (lengthET4.length() > 0) {
String L4 = lengthET4.getText().toString();
Le4 = Float.parseFloat(L4);
}
float Di4 = 0;
if (diameterET4.length() > 0) {
String D4 = diameterET4.getText().toString();
Di4 = Float.parseFloat(D4);
}
float Le5 = 0;
if (lengthET5.length() > 0) {
String L5 = lengthET5.getText().toString();
Le5 = Float.parseFloat(L5);
}
float Di5 = 0;
if (diameterET5.length() > 0) {
String D5 = diameterET5.getText().toString();
Di5 = Float.parseFloat(D5);
}
final float Surface1 = (float) (Le1 * Di1 * Math.PI);
final float Surface2 = (float) (Le2 * Di2 * Math.PI);
final float Surface3 = (float) (Le3 * Di3 * Math.PI);
final float Surface4 = (float) (Le4 * Di4 * Math.PI);
final float Surface5 = (float) (Le5 * Di5 * Math.PI);
final float Surface = Surface1 + Surface2 + Surface3 + Surface4 + Surface5;
Intent intent = new Intent(MainActivity.this, IntensityActivity.class);
if (Surface == 0) {
Toast.makeText(MainActivity.this, "No numbers are entered", Toast.LENGTH_SHORT).show();
} else {
intent.putExtra("Result", Surface);
startActivity(intent);
}
PersonalInfoSharedPrefManager manager = new PersonalInfoSharedPrefManager(MainActivity.this);
manager.setSuface(Surface);
Project project = new Project();
project.setLength1(lengthET1.getText().toString());
project.setDiameter1(diameterET1.getText().toString());
project.setLength2(lengthET2.getText().toString());
project.setDiameter2(diameterET2.getText().toString());
project.setLength3(lengthET3.getText().toString());
project.setDiameter3(diameterET3.getText().toString());
project.setLength4(lengthET4.getText().toString());
project.setDiameter4(diameterET4.getText().toString());
project.setLength5(lengthET5.getText().toString());
project.setDiameter5(diameterET5.getText().toString());
projectDAO.updateProject(project);
}
});
}
}
In MainActivity you should set your project id for update:
Project project = new Project();
project.setId(yourIdValue);
Your updateProject method is roughly saying update values (as per the Contentvalues) where the project id is whatever is returned from the project's getID method.
However when you create the project to be passed to the method you don't provide the id (which should be as per the row added in the database) so it will be some arbitrary value perhaps null (can't say as the Project class isn't included in your code.)
So that's the cause.
There could be a number of fixes. One would be to get the id (very much the preferable/standard method as identifying a row is why you use an id column).
You can retrieve this when adding the project to the database by instead of returning false if the SQLiteDatabase method returns -1 by instead returning the value (the id of the inserted row). You can then check if that is -1 or less than 1 (id will be 1 or greater), which will indicate that the row was not added. If the value is 1 or greater, then the row has been inserted.
You could then pass the id via an IntentExtra to the MainActivity where you would extract and set the projects id to the value. Note you should ideally use long for the id as it can be up to a 64 bit signed Integer (Normally it is 1 then 2 then 3 etc.......).
Another way would be to identify the project from the database according to other know stored values that can uniquely identify the project and then alter the WHERE clause of the updateProject method (the 3rd and 4th parameters).
Another way would be to extract the id using the identifying information (so a permutation of the above)
Suggested fix
Note this is in-principle code, it has not been tested so may contain some errors:-
Comments have been include to identify the changes. they will typically be //<<<< followed some indication of that has been done.
1) Amend the addProject method to return the id else -1 :-
#Override
public long addProject(Project project) { //<<<< CHANGED
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", project.getName());
contentValues.put("company_name", project.getCompany_name());
contentValues.put("address", project.getAddress());
contentValues.put("length1",project.getLength1());
contentValues.put("length2",project.getLength2());
contentValues.put("length3",project.getLength3());
contentValues.put("length4",project.getLength4());
contentValues.put("length5",project.getLength5());
contentValues.put("diameter1",project.getDiameter1());
contentValues.put("diameter2",project.getDiameter2());
contentValues.put("diameter3",project.getDiameter3());
contentValues.put("diameter4",project.getDiameter4());
contentValues.put("diameter5",project.getDiameter5());
long result = db.insert("tbl_project_info", null, contentValues);
db.close();
return result; //<<<< CHANGED
}
2) Pass the id from the NewProjectActivity for the MainActivity :-
saveInfoBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long projectid = -1; //<<<< LINE ADDED
if (projectNameET.length() > 0) {
if (companyNameET.length() > 0) {
if (addressET.length() > 0) {
Project project = new Project();
project.setName(projectNameET.getText().toString());
project.setCompany_name(companyNameET.getText().toString());
project.setAddress(addressET.getText().toString());
projectid = projectDAO.addProject(project); //<<<< LINE ADDED
if (projectid > 0){ //<<<< LINE CHANGED
Toast.makeText(NewProjectActivity.this, "Success", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(NewProjectActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
}
}
Intent intent = new Intent(NewProjectActivity.this,MainActivity.class);
intent.putExtra("IE_PROJECTID",projectid); //<<<< ADDED
startActivity(intent);
}
});
}
3) Retrieve the id in the MainActivity :-
private long mProjectID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
projectDAO = DBInjector.provideProjectDao(this);
//<<<< ADDED folowing lines to get the id from the intent >>>>
mProjectID = getIntent().getLongExtra(
"IE_PROJECTID",
0 //<<<< NOTE default could be -1 (or any negative) as long as it's less than 1
);
.........
project.setID(mProjectID); //<<<< ADDED might need setter in project
projectDAO.updateProject(project);
use of "IE_PROJECTID" could be replaced with constant, there are some stock ones that can be utilised like Intent.EXTRA_????????? (where ????????? represents many values)
I'm trying to populate a ListView from an SQLiteDatabase using a SimpleCursorAdapter. There are no errors, and I know the database has data in it, but nothing shows up on the ListView.
Can anyone help find what is going wrong?
1) Layout for the ListView(activity_profilelist.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_profilelist"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation= "vertical"
android:paddingBottom="0dp"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
tools:context="com.corvus.corvusenterprises.digimonapp.Profilelist">
<TextView
android:id="#+id/textView_names"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.1"
android:gravity="center"
android:textAppearance="#android:style/TextAppearance.Theme"
android:textSize="25sp"
android:text="Digimon"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation= "horizontal">
<ListView
android:id="#+id/ListView_names"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="100" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_weight="0.1">
<Button
android:id="#+id/button_update"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:text="Update List">
</Button>
</LinearLayout>
</LinearLayout>
2)Layout for the individual entries in the ListView(activity_list_example.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/Digimon_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="28sp" />
<TextView
android:id="#+id/Digimon_favourites"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="28sp" />
</LinearLayout>
3)Java for the ListView(ProfileList.java)
package com.corvus.corvusenterprises.digimonapp;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import static com.corvus.corvusenterprises.digimonapp.R.id.button_update;
public class Profilelist extends Digimon2 {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profilelist);
DBHelper dbHelper = DBHelper.getInstance(MyApp.getContext());
Cursor cursor = dbHelper.defaultMainMenu();
String[]columns = new String[] {"name","favourite","path"};
ListView theListView = (ListView) findViewById(R.id.listView_names);
int[]to = new int[] {R.id.Digimon_name,R.id.Digimon_favourites};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.activity_list_example,cursor,columns,to,0);
theListView.setAdapter(adapter);
}
}
4)Java for the Database Helper(DBHelper.java)
package com.corvus.corvusenterprises.digimonapp;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.content.ContentValues;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import org.jsoup.Jsoup;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import static android.graphics.Bitmap.Config.ARGB_8888;
import static android.graphics.Bitmap.createBitmap;
/**
* Created by Jack on 28-Mar-17.
*/
public class DBHelper extends SQLiteOpenHelper {
private static final int version = 1;
private static final String DATABASE_NAME = "DigimonDatabase.db";
private static final String DIGIMON_TABLE_NAME = "Digimon";
private static final String DIGIMON_COLUMN_NAME = "name";
private static final String DIGIMON_COLUMN_DUB_NAME = "dub_name";
private static final String DIGIMON_COLUMN_LEVEL = "level";
private static final String DIGIMON_COLUMN_ATTRIBUTE = "attribute";
private static final String DIGIMON_COLUMN_DESCRIPTION = "description";
private static final String DIGIMON_COLUMN_FAVOURITE = "favourite";
private static final String EVOLUTIONS_TABLE_NAME = "Evolutions";
private static final String EVOLUTIONS_COLUMN_FROM = "\"from\"";
private static final String EVOLUTIONS_COLUMN_TO = "\"to\"";
private static final String EVOLUTIONS_COLUMN_CONDITIONS = "conditions";
private static final String ATTACKS_TABLE_NAME = "Attacks";
private static final String ATTACKS_COLUMN_NAME = "name";
private static final String ATTACKS_COLUMN_DUB_NAME = "dub_name";
private static final String ATTACKS_COLUMN_DIGIMON = "digimon";
private static final String ATTACKS_COLUMN_DESCRIPTION = "description";
private static final String PICTURES_TABLE_NAME = "Pictures";
private static final String PICTURES_COLUMN_DIGIMON = "digimon";
private static final String PICTURES_COLUMN_PATH = "path";
private static String[]digimonArray = {/*19MB worth of Digimon names removed for length constraints.*/};
private static boolean[]presentDigimon = new boolean[digimonArray.length];
private static DBHelper instance;
private DBHelper(Context context)
{
super(context, DATABASE_NAME, null, version);
}
public static DBHelper getInstance(Context ctx)
{
if(instance == null)
instance = new DBHelper(ctx);
return instance;
}
#Override
public void onCreate(SQLiteDatabase db)
{
//Create and define the tables
db.execSQL("CREATE TABLE "+DIGIMON_TABLE_NAME+" ("+DIGIMON_COLUMN_NAME+" TEXT PRIMARY KEY, "+DIGIMON_COLUMN_DUB_NAME+" TEXT NULL, "+DIGIMON_COLUMN_LEVEL+" TEXT NULL, "+DIGIMON_COLUMN_ATTRIBUTE+" TEXT NULL, "+DIGIMON_COLUMN_DESCRIPTION+" TEXT NULL, "+DIGIMON_COLUMN_FAVOURITE+" TEXT DEFAULT 'FALSE')");
db.execSQL("CREATE TABLE "+EVOLUTIONS_TABLE_NAME+" ("+EVOLUTIONS_COLUMN_FROM+" TEXT, "+EVOLUTIONS_COLUMN_TO+" TEXT, "+EVOLUTIONS_COLUMN_CONDITIONS+" TEXT NULL, primary key("+EVOLUTIONS_COLUMN_FROM+", "+EVOLUTIONS_COLUMN_TO+"))");
db.execSQL("CREATE TABLE "+ATTACKS_TABLE_NAME+" ("+ATTACKS_COLUMN_NAME+" TEXT, "+ATTACKS_COLUMN_DUB_NAME+" TEXT NULL, "+ATTACKS_COLUMN_DIGIMON+" TEXT, "+ATTACKS_COLUMN_DESCRIPTION+" TEXT NULL, primary key("+ATTACKS_COLUMN_NAME+", "+ATTACKS_COLUMN_DIGIMON+"))");
db.execSQL("CREATE TABLE "+PICTURES_TABLE_NAME+" ("+PICTURES_COLUMN_DIGIMON+" TEXT PRIMARY KEY, "+PICTURES_COLUMN_PATH+" TEXT)");
//Fill in some default Digimon
insertDigimon("Guilmon", "Guilmon", "Child/Rookie", "Virus", "Dinosaur", "TRUE");
insertDigimon("Growmon", "Growlmon", "Adult/Champion", "Virus", "Bigger Dinosaur", "FALSE");
insertDigimon("Terriermon", "terriermon", "Child/Rookie", "Vaccine", "Dogbunny", "FALSE");
insertDigimon("Galgomon", "Gargomon", "Adult/Champion", "Vaccine", "Gunbunny", "FALSE");
insertDigimon("Kyubimon", "Kyubimon", "Adult/Champion", "Data", "9-Tailed Fox", "FALSE");
insertDigimon("Taomon", "Taomon", "Perfect/Ultimate", "Data", "Kitsune Miko", "FALSE");
insertDigimon("Impmon", "Impmon", "Child/Rookie", "Virus", "Kid in a purple onesie", "FALSE");
insertDigimon("Beelzebumon", "Beelzemon", "Ultimate/Mega", "Virus", "Demon Lord of Gluttony", "FALSE");
presentDigimon[460] = true; presentDigimon[454] = true;
presentDigimon[1019] = true; presentDigimon[374] = true;
presentDigimon[572] = true; presentDigimon[1013] = true;
presentDigimon[507] = true; presentDigimon[100] = true;
insertEvolution("Guilmon", "Growmon");
insertEvolution("Terriermon", "Galgomon");
insertEvolution("Kyubimon", "Taomon");
insertEvolution("Impmon", "Beelzebumon", "(Warp Evolution)");
insertAttack("Fireball", "Pyro Sphere", "Guilmon", "Explosive Fireball");
insertAttack("Rock Breaker", "Rock Breaker", "Guilmon", "Claw Swipe");
insertAttack("Exhaust Flame", "Pyro Blaster", "Growmon", "Fire Laser");
insertAttack("Plasma Blade", "Dragon Slash", "Growmon", "Forearm Blades");
insertAttack("Blazing Fire", "Bunny Blast", "Terriermon", "Energy Blast");
insertAttack("Petit Twister", "Terrier Tornado", "Terriermon", "Throws Tornado");
insertAttack("Gatling Arm", "Gargo Laser", "Galgomon", "Fires Guns");
insertAttack("Dum Dum Upper", "Bunny Pummel", "Galgomon", "Fires Guns While Punching");
insertAttack("Koenryu", "Dragon Wheel", "Kyubimon", "Fire Dragon");
insertAttack("Onibidama", "Fox-Tail Inferno", "Kyubimon", "Fireballs from the tails");
insertAttack("Bonhitsusen", "Talisman of Light", "Taomon", "Energy Seal Laser");
insertAttack("Oṃ", "Talisman Spell", "Taomon", "Makes a dome shield");
insertAttack("Night of Fire", "Badaboom", "Impmon", "Mini-Fireballs");
insertAttack("Pillar of Fire", "", "Impmon", "Wall of Flames");
insertAttack("Double Impact", "Double Impact", "Beelzebumon", "Fires two bullets");
insertAttack("Darkness Claw", "", "Beelzebumon", "Kills Leomon");
insertPicture("Guilmon","R.mipmap.guilmon.jpg");
insertPicture("Growmon","R.mipmap.growmon.jpg");
insertPicture("Terriermon","R.mipmap.terriermon.jpg");
insertPicture("Galgomon","R.mipmap.galgomon.jpg");
insertPicture("Kyubimon","R.mipmap.kyubimon.jpg");
insertPicture("Taomon","R.mipmap.taomon.jpg");
insertPicture("Impmon","R.mipmap.impmon.jpg");
insertPicture("Beelzebumon","R.mipmap.beelzebumon.jpg");
//Populate Tables
new Downloader().start();
}
private class Downloader extends Thread
{
public void run()
{
int digimonToGetAtOnce = 20;
HttpURLConnection connection;
URL url;
String wikimonAddress, downloadResult;
BufferedInputStream in;
for(int i=0;i<digimonToGetAtOnce;)
{
int rand = (int)(Math.random()*digimonArray.length);
if(!presentDigimon[rand])
{
wikimonAddress = "https://wikimon.net/api.php?action=parse&format=json&page=" + digimonArray[rand] + "&prop=text";
try {
url = new URL(wikimonAddress);
connection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(connection.getInputStream());
downloadResult = readStream(in);
connection.disconnect();
i++;
presentDigimon[rand] = true;
sortInput(downloadResult);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private String readStream(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(is),1000);
for (String line = r.readLine(); line != null; line =r.readLine()){
sb.append(line);
}
is.close();
return sb.toString();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldver, int newVer)
{
db.execSQL("DROP TABLE IF EXISTS "+DIGIMON_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS "+ATTACKS_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS "+EVOLUTIONS_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS "+PICTURES_TABLE_NAME);
onCreate(db);
}
public void insertDigimon(String name, String dub_name, String level, String attribute, String description, String favourite)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DIGIMON_COLUMN_NAME,name);
values.put(DIGIMON_COLUMN_DUB_NAME,dub_name);
values.put(DIGIMON_COLUMN_LEVEL,level);
values.put(DIGIMON_COLUMN_ATTRIBUTE,attribute);
values.put(DIGIMON_COLUMN_DESCRIPTION,description);
values.put(DIGIMON_COLUMN_FAVOURITE, favourite);
db.insert(DIGIMON_TABLE_NAME, null, values);
db.close();
}
public void insertAttack(String name, String dub_name, String digimon, String description)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ATTACKS_COLUMN_NAME, name);
values.put(ATTACKS_COLUMN_DUB_NAME,dub_name);
values.put(ATTACKS_COLUMN_DIGIMON, digimon);
values.put(ATTACKS_COLUMN_DESCRIPTION, description);
db.insert(ATTACKS_TABLE_NAME, null, values);
db.close();
}
public void insertEvolution(String from, String to, String conditions)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(EVOLUTIONS_COLUMN_TO,to);
values.put(EVOLUTIONS_COLUMN_FROM,from);
values.put(EVOLUTIONS_COLUMN_CONDITIONS,conditions);
db.insert(EVOLUTIONS_TABLE_NAME, null, values);
db.close();
}
public void insertEvolution(String from, String to)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(EVOLUTIONS_COLUMN_TO,to);
values.put(EVOLUTIONS_COLUMN_FROM,from);
db.insert(EVOLUTIONS_TABLE_NAME, null, values);
db.close();
}
public void insertPicture(String digimon, String path)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PICTURES_COLUMN_DIGIMON,digimon);
values.put(PICTURES_COLUMN_PATH,path);
db.insert(PICTURES_TABLE_NAME, null, values);
db.close();
}
public Cursor defaultMainMenu()
{
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT "+DIGIMON_TABLE_NAME+".ROWID AS _id, "+DIGIMON_COLUMN_NAME+", "+DIGIMON_COLUMN_FAVOURITE+" FROM "+DIGIMON_TABLE_NAME;
Cursor cursor = db.rawQuery(query,null);
int dummy = cursor.getCount();
db.close();
return cursor;
}
public Cursor searchMenuQuery(String search)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT ROWID AS _id, "+DIGIMON_COLUMN_NAME+", "+DIGIMON_COLUMN_FAVOURITE+", "+PICTURES_TABLE_NAME+"."+PICTURES_COLUMN_PATH+" FROM "+DIGIMON_TABLE_NAME+" JOIN "+PICTURES_TABLE_NAME+" ON "+PICTURES_TABLE_NAME+"."+PICTURES_COLUMN_DIGIMON+"="+DIGIMON_TABLE_NAME+"."+DIGIMON_COLUMN_NAME +" WHERE "+DIGIMON_COLUMN_NAME+" LIKE '%"+search+"%' UNION SELECT ROWID AS _id, "+DIGIMON_COLUMN_NAME+", "+DIGIMON_COLUMN_FAVOURITE+", "+PICTURES_TABLE_NAME+"."+PICTURES_COLUMN_DIGIMON+" FROM "+DIGIMON_TABLE_NAME+" JOIN "+PICTURES_TABLE_NAME+" ON "+PICTURES_TABLE_NAME+"."+PICTURES_COLUMN_DIGIMON+"="+DIGIMON_TABLE_NAME+"."+DIGIMON_COLUMN_NAME +" WHERE "+DIGIMON_COLUMN_DUB_NAME+" LIKE '%"+search+"%'";
Cursor cursor = db.rawQuery(query,null);
int dummy = cursor.getCount();
db.close();
return cursor;
}
public Cursor favouritesMenuQuery()
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT ROWID AS _id, "+DIGIMON_COLUMN_NAME+", "+PICTURES_TABLE_NAME+"."+PICTURES_COLUMN_PATH+" FROM "+DIGIMON_TABLE_NAME+" JOIN "+PICTURES_TABLE_NAME+" ON "+PICTURES_TABLE_NAME+"."+PICTURES_COLUMN_DIGIMON+"="+DIGIMON_TABLE_NAME+"."+DIGIMON_COLUMN_NAME +" WHERE "+DIGIMON_COLUMN_FAVOURITE+" = 'TRUE'";
Cursor cursor = db.rawQuery(query,null);
int dummy = cursor.getCount();
db.close();
return cursor;
}
public Cursor digimonProfileQuery(String name)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT ROWID AS _id, * FROM "+DIGIMON_TABLE_NAME+" WHERE "+DIGIMON_COLUMN_NAME+" = '"+name+"'";
Cursor cursor = db.rawQuery(query, null);
int dummy = cursor.getCount();
db.close();
return cursor;
}
public Cursor digimonAttacksQuery(String name)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT ROWID AS _id, * FROM "+ATTACKS_TABLE_NAME+" WHERE "+ATTACKS_COLUMN_DIGIMON+" = '"+name+"'";
Cursor cursor = db.rawQuery(query, null);
int dummy = cursor.getCount();
db.close();
return cursor;
}
public Cursor digimonEvolutionFromQuery(String name)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT ROWID AS _id, * FROM "+EVOLUTIONS_TABLE_NAME+" WHERE "+EVOLUTIONS_COLUMN_FROM+" = '"+name+"'";
Cursor cursor = db.rawQuery(query, null);
int dummy = cursor.getCount();
db.close();
return cursor;
}
public Cursor digimonEvolutionToQuery(String name)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT ROWID AS _id, * FROM "+EVOLUTIONS_TABLE_NAME+" WHERE "+EVOLUTIONS_COLUMN_TO+" = '"+name+"'";
Cursor cursor = db.rawQuery(query, null);
int dummy = cursor.getCount();
db.close();
return cursor;
}
public Cursor digimonPictureQuery(String name)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT ROWID AS _id, "+PICTURES_COLUMN_PATH+" FROM "+PICTURES_TABLE_NAME+" WHERE "+PICTURES_COLUMN_DIGIMON+" = '"+name+"'";
Cursor cursor = db.rawQuery(query, null);
int dummy = cursor.getCount();
db.close();
return cursor;
}
public void sortInput(String input)
{
int index1, index2;
String name, dubName, level, attribute, description, imageUrl, imagePath;
String attackName="", attackDubName="", attackDescription="No description given.";
String from = "", to = "", conditions = "";
ArrayList<String[]> attacks = new ArrayList<String[]>();
ArrayList<String[]> evolvesFrom = new ArrayList<String[]>();
ArrayList<String[]> evolvesTo = new ArrayList<String[]>();
boolean tableEnded = false, rowEnded = false;
index2 = input.indexOf("\",\n\"pageid\":");
name = input.substring(20,index2);
index1 = input.indexOf("Japanese</b></span></span><br />")+32;
index2 = input.indexOf("\\n</td></tr>\\n<tr>\\n<td style=\\\"border-top:1px solid gray\\\" align=\\\"center\\\"><span class=\\\"plainlinks\\\">",index1);
description = input.substring(index1, index2);
description = Jsoup.parse(description).text();
if(input.contains("<b>Dub:</b>\\n</td>\\n<td>\\n</td>\\n<td>\\n</td>\\n<td valign=\\\"center\\\"><i>"))
{
index1 = input.indexOf("<b>Dub:</b>\\n</td>\\n<td>\\n</td>\\n<td>\\n</td>\\n<td valign=\\\"center\\\"><i>")+72;
index2 = input.indexOf("</i>",index1);
dubName = input.substring(index1,index2);
}
else dubName = name;
index1 = input.indexOf("Level</font></a></b>\\n</td>\\n<td style=\\\"background:#252525;width:175px;border-bottom:1px solid #808080\\\"><a href=\\\"/")+118;
index2 = input.indexOf("\\\" title=\\\"",index1);
level = input.substring(index1,index2);
index1 = input.indexOf("Attribute</font></a></b>\\n</td>\\n<td style=\\\"background:#252525;width:175px;border-bottom:1px solid #808080\\\"><a href=\\\"/Category:")+136;
index2 = input.indexOf("\\\" title=\\\"",index1);
attribute = input.substring(index1,index2);
index2 = input.indexOf("width=\\\"320\\\" height=\\\"320\\\"");
index1 = input.lastIndexOf("src=\\\"",index2);
imageUrl = "https://wikimon.net"+input.substring(index1,index2);
index1 = input.indexOf("<i><b>")+6;
index2 = input.indexOf("</b></i>",index1);
for(int i = 0;!tableEnded;i++)
{
//name, dub_name, digimon, description
attackName = input.substring(index1,index2);
index1 = input.indexOf("<i>",index2)+3;
index2 = input.indexOf("</i>",index1);
attackDubName = input.substring(index1,index2);
index1 = input.indexOf("</td>",index2);
index1 = input.indexOf("</td>",index1);
index1 = input.indexOf("</td>",index1);
index1 = input.indexOf("<i>",index1)+3;
index2 = input.indexOf("</i>",index1);
if(input.substring(index1,index2).compareTo("<br />")!=0)
attackDubName = input.substring(index1,index2);
else if(attackDubName.compareTo("<br />")==0)
attackDubName = attackName;
index1 = input.indexOf("<td style",index2);
index1 = input.indexOf("\\\">",index1)+3;
index2 = input.indexOf("\\n</td></tr>");
attackDescription = input.substring(index1,index2);
attacks.add(i,new String[]{attackName,attackDubName,name,attackDescription});
if(input.substring(index2,index2+64).contains("</table>"))
{
tableEnded = true;
}
}
tableEnded = false;
for(int i = 0;!tableEnded;i++)
{
index1 = input.indexOf("<li>",index2);
index1 = input.indexOf("\\\"/",index1)+3;
index2 = input.indexOf("\\\" title",index1);
from = input.substring(index1,index2);
index1 = input.indexOf("</a>",index2);
index2 = input.indexOf("</li>",index1);
if(Jsoup.parse(input.substring(index1,index2)).text().contains("("))
{
conditions = Jsoup.parse(input.substring(index1,index2)).text();
evolvesFrom.add(new String[]{from,name,conditions});
}
else evolvesFrom.add(new String[]{from,name});
if(input.substring(index1,index1+9).contains("</ul>"))
{
tableEnded = true;
}
}
tableEnded = false;
for(int i = 0;!tableEnded;i++)
{
index1 = input.indexOf("<li>",index2);
index1 = input.indexOf("\\\"/",index1)+3;
index2 = input.indexOf("\\\" title",index1);
to = input.substring(index1,index2);
index1 = input.indexOf("</a>",index2);
index2 = input.indexOf("</li>",index1);
if(Jsoup.parse(input.substring(index1,index2)).text().contains("("))
{
conditions = Jsoup.parse(input.substring(index1,index2)).text();
evolvesTo.add(new String[]{name,to,conditions});
}
else evolvesTo.add(new String[]{name,to});
if(input.substring(index1,index1+9).contains("</ul>"))
{
tableEnded = true;
}
}
insertDigimon(name,dubName,level,attribute,description,"FALSE");
for(int i=0;i<attacks.size();i++)
{
insertAttack(attackName,attackDubName,name,attackDescription);
}
for(int i=0;i<evolvesFrom.size();i++)
{
if(evolvesFrom.get(i).length==3)
insertEvolution(evolvesFrom.get(1)[0],name,evolvesFrom.get(1)[2]);
else
insertEvolution(evolvesFrom.get(1)[0],name);
}
for(int i=0;i<evolvesTo.size();i++)
{
if(evolvesTo.get(i).length==3)
insertEvolution(name,evolvesTo.get(1)[1],evolvesTo.get(1)[2]);
else
insertEvolution(name,evolvesTo.get(1)[1]);
}
new DownloadFile().execute(imageUrl,name);
insertPicture(name,"/res/mipmap/xxxhdpi/"+name+".jpg");
}
class DownloadFile extends AsyncTask<String,Integer,Long> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Long doInBackground(String... aurl) {
int count;
try {
URL url = new URL((String) aurl[0]);
URLConnection connection = url.openConnection();
connection.connect();
String targetFileName=aurl[1]+".jpg";
int lengthOfFile = connection.getContentLength();
String PATH = Environment.getExternalStorageDirectory()+ "/res/mipmap/xxxhdpi/";
File folder = new File(PATH);
if(!folder.exists()){
folder.mkdir();//If there is no folder it will be created.
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(PATH+targetFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress ((int)(total*100/lengthOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
}
}
Any and all help is welcome.
There is problem with your simple cursor adapter,
Here you provide three columns
String[]columns = new String[] {"name","favourite","path"};
but here you supply only two views:
int[]to = new int[] {R.id.Digimon_name,R.id.Digimon_favourites};
also in your raw query
String query = "SELECT "+DIGIMON_TABLE_NAME+".ROWID AS _id,
"+DIGIMON_COLUMN_NAME+", "+DIGIMON_COLUMN_FAVOURITE+" FROM
"+DIGIMON_TABLE_NAME;
you provided only "_id", "name" and "favorite" columns and not the "path".
**EDIT: I'll use listview instead of Gridview. **
I've been learning Android since a couple of weeks and last days I've been struggling on getting my SQL-data in a gridview. I've been searching through many, many topics and I can't seem to find a fitting answer to my question. This is the code I've got so far:
package com.example.myfirstapp;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class DisplayMessageActivity extends AppCompatActivity {
public static ArrayList<String> ArrayofName = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String selectQuery = "SELECT * FROM " + MainActivity.FeedReaderContract.FeedEntry.TABLE_NAME;
Cursor cursor = db.rawQuery(selectQuery, null);
{
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
String id = cursor.getString(cursor.getColumnIndex("_ID"));
String title = cursor.getString(cursor.getColumnIndex("title"));
String subtitle = cursor.getString(cursor.getColumnIndex("subtitle"));
String name = id +"\n" + title +"\n"+ subtitle;
DisplayMessageActivity.ArrayofName.add(name);
} while (cursor.moveToNext());
}
}
GridView gridView = (GridView) findViewById(R.id.gridView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ArrayofName);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) v).getText(), Toast.LENGTH_SHORT).show();
}
});
}
private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + MainActivity.FeedReaderContract.FeedEntry.TABLE_NAME + " (" +
MainActivity.FeedReaderContract.FeedEntry._ID + " INTEGER PRIMARY KEY," +
MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE + TEXT_TYPE + " )";
private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS '" + MainActivity.FeedReaderContract.FeedEntry.TABLE_NAME + "'";
public class FeedReaderDbHelper extends SQLiteOpenHelper {
// If you change the database schema, you must increment the database version.
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "FeedReader.db";
public FeedReaderDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
}
DisplayMessageActivity.FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(this);
public void Test (View view) {
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Define a projection that specifies which columns from the database you will actually use after this query.
String[] projection = {MainActivity.FeedReaderContract.FeedEntry._ID, MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE};
// Filter results WHERE "title" = 'My Title'
String selection = MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE + " = ?";
String[] selectionArgs = {"A"};
// How you want the results sorted in the resulting Cursor
String sortOrder = MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";
Cursor c = db.query(
MainActivity.FeedReaderContract.FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
if (c.getCount()>0) {
c.moveToFirst();
int itemId = c.getInt(c.getColumnIndexOrThrow(MainActivity.FeedReaderContract.FeedEntry._ID));
String strTitel = c.getString(c.getColumnIndexOrThrow(MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE));
String strSubtitel = c.getString(c.getColumnIndexOrThrow(MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE));
EditText edtID = (EditText) findViewById(R.id.txtInvoer);
edtID.setText(Integer.toString(itemId));
EditText edtTitle = (EditText) findViewById(R.id.txtTitel2);
edtTitle.setText(strTitel);
EditText edtSubtitle = (EditText) findViewById(R.id.txtSubtitel2);
edtSubtitle.setText(strSubtitel);
} else {
Toast.makeText(getApplicationContext(), "Geen data in db", Toast.LENGTH_LONG).show();
}
}
public void Vorige (View view) {
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {MainActivity.FeedReaderContract.FeedEntry._ID, MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE};
String selection = "_ID=?";
EditText edtGeselecteerdeID = (EditText) findViewById(R.id.txtInvoer);
int intVolgendeID=Integer.parseInt(edtGeselecteerdeID.getText().toString())-1;
String strVolgendeID=Integer.toString(intVolgendeID);
String[] selectionArgs = {strVolgendeID};
// How you want the results sorted in the resulting Cursor
String sortOrder = MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";
Cursor c = db.query(
MainActivity.FeedReaderContract.FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
if (c.getCount()>0) {
c.moveToFirst();
int itemId = c.getInt(c.getColumnIndexOrThrow(MainActivity.FeedReaderContract.FeedEntry._ID));
String strTitel = c.getString(c.getColumnIndexOrThrow(MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE));
String strSubtitel = c.getString(c.getColumnIndexOrThrow(MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE));
EditText edtID = (EditText) findViewById(R.id.txtInvoer);
edtID.setText(Integer.toString(itemId));
EditText edtTitle = (EditText) findViewById(R.id.txtTitel2);
edtTitle.setText(strTitel);
EditText edtSubtitle = (EditText) findViewById(R.id.txtSubtitel2);
edtSubtitle.setText(strSubtitel);
} else {
Toast.makeText(getApplicationContext(), "Geen data in db", Toast.LENGTH_LONG).show();
}
}
public void Volgende (View view) {
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {MainActivity.FeedReaderContract.FeedEntry._ID, MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE};
String selection = MainActivity.FeedReaderContract.FeedEntry._ID + " = ?";
EditText edtGeselecteerdeID = (EditText) findViewById(R.id.txtInvoer);
int intVolgendeID=Integer.parseInt(edtGeselecteerdeID.getText().toString())+1;
String strVolgendeID=Integer.toString(intVolgendeID);
String[] selectionArgs = {strVolgendeID};
// How you want the results sorted in the resulting Cursor
String sortOrder = MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";
Cursor c = db.query(
MainActivity.FeedReaderContract.FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
if (c.getCount()>0) {
c.moveToFirst();
int itemId = c.getInt(c.getColumnIndexOrThrow(MainActivity.FeedReaderContract.FeedEntry._ID));
String strTitel = c.getString(c.getColumnIndexOrThrow(MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE));
String strSubtitel = c.getString(c.getColumnIndexOrThrow(MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE));
EditText edtID = (EditText) findViewById(R.id.txtInvoer);
edtID.setText(Integer.toString(itemId));
EditText edtTitle = (EditText) findViewById(R.id.txtTitel2);
edtTitle.setText(strTitel);
EditText edtSubtitle = (EditText) findViewById(R.id.txtSubtitel2);
edtSubtitle.setText(strSubtitel);
} else {
Toast.makeText(getApplicationContext(), "Geen data in db", Toast.LENGTH_LONG).show();
}
}
}
So in MainActivity I've got code to add data into the database. 'DisplayMessageActivity' is for testing out new stuff. My database consists of 3 columns: ID, title and subtitle. I use the method 'Test' to display the data in Edittext objects, and the methods 'Vorige' and 'Volgende' to go through the data. Now I'm trying to display the data (id, title & subtitle) in a gridview or listview (I don't really know what to use). You can find all the code for my problem in the first onCreate class.
I'd like to achieve something like this:
So the first row displays the different column titles, and all the other rows display the data. The first row displaying the titles aren't even needed, I could easily add them by using EditText fields.
Can anyone help me out here? Other suggestions for improving my code are always welcome too ;)
Hello Techie :) i am new to android . i'm developing one app where user is registering with all personal detail and mobile device detail and after user login all the things working fine and met with result but when i'm moving to admin section here i have issue and i'm not getting any idea about this .
Parts of Admin section where i am stuck :-
1) after admin login , all table records should be shown in one table layout here u can say i want to populate all table records in Table Layout .
i try with specific user name and its showing in the table layout but it's not my requirement , i have to show all users in Table layout .
i'm sharing my code here , will u all suggest me what to do next and how can i achieve my requirement.
Thanks for your valuable time :)
//MainActivity.java
package com.example.yadapras.mobiltyemp;
import android.content.Context;
import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.VectorEnabledTintResources; import android.telephony.TelephonyManager; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;
/** * Created by yadapras on 6/26/2016. */ public class MainActivity extends AppCompatActivity {
EditText a,b;
String usr,pass;
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonClick(View v)
{
if (v.getId() == R.id.BLogin)
{
a = (EditText)findViewById(R.id.userName);
usr = a.getText().toString();
b = (EditText)findViewById(R.id.userPassword);
pass = b.getText().toString();
String password = null;
if( a.getText().toString().length() == 0 || usr == "" || usr == null)
a.setError( " User name is required!" );
if( b.getText().toString().length() == 0 || pass =="" || pass == null)
b.setError( "Password is required!" );
else{
password = helper.searchPass(usr);
}
if (a.getText().toString().equals("admin") && b.getText().toString().equals("admin"))
{
Intent intent = new Intent(getApplicationContext(), AdminDisplay.class);
startActivity(intent);
}else{
if (pass.equals(password) && password != null) {
Intent intent = new Intent(getApplicationContext(), EmpDetail.class);
intent.putExtra("usr", usr);
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String uid = telephonyManager.getDeviceId();
String manufacturer = Build.MANUFACTURER; // Not used in current scenario
String model = Build.MODEL;
int version = Build.VERSION.SDK_INT;
String versionRelease = Build.VERSION.RELEASE; // not used in current scenario
String msg = "IMEI No: " + uid + "\n" + "Manufacturer is :" + manufacturer + "\n" + "Model is :" + model + "\n" + "Os Version is :" + version + "\n" + "VersionRelease is :" + versionRelease;
Toast toast = Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG);
toast.show();
Register r = new Register();
r.setImei_no(uid);
r.setDev_model(model);
r.setOs_version(version);
r.setUname(usr);
helper.updateTable(r); /*For updating table with new Coloumn*/
startActivity(intent);
}
else
{
Toast err_pass = Toast.makeText(MainActivity.this,"UserName and Password don't Match",Toast.LENGTH_SHORT);
err_pass.show();
}
}
}
if (v.getId() == R.id.BSignup)
{
Intent intent = new Intent(getApplicationContext(), Registration.class);
startActivity(intent);
}
}
}
//DatabaseHelper.java
package com.example.yadapras.mobiltyemp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.ArrayMap;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by yadapras on 7/8/2016.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "registrationDB.db";
public static final String TABLE_NAME = "registrations";
public static final String COLUMN_ID = "id";
public static final String COLUMN_USERNAME = "username";
public static final String COLUMN_PASSWORD= "password";
public static final String COLUMN_RE_PASSWORD= "re_password";
public static final String COLUMN_NAME= "name";
public static final String COLUMN_EMAIL= "email";
public static final String COLUMN_PHONE_NO= "phone_no";
/*Adding three coloumn IMEI_NO,OS_Version,Model_Device Respectively*/
public static final String COLUMN_IMEI_NO = "imei_no";
public static final String COLUMN_DEV_MODEL = "dev_model";
public static final String COLUMN_OS_VERSION = "os_version";
SQLiteDatabase sqLiteDatabase;
private static final String TABLE_CREATE = "create table registrations(id integer primary key not null, " +
"username text not null, password text not null, re_password text not null, name text not null, email text not null," +
"phone_no number not null,imei_no text, dev_model text, os_version text);";
public DatabaseHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(TABLE_CREATE);
this.sqLiteDatabase=sqLiteDatabase;
Log.d("#####Table Value",TABLE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String query = "DROP TABLE IF EXISTS " +TABLE_NAME ;
sqLiteDatabase.execSQL(query);
this.onCreate(sqLiteDatabase);
}
public void registerUser(Register r) {
/*Inserting anything in to the dataBase make sure it should be writable*/
sqLiteDatabase = getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from registrations";
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
int count = cursor.getCount();
Log.d("##count",""+count);
values.put(COLUMN_ID,count);
Log.d("##id",r.getUname());
values.put(COLUMN_USERNAME,r.getUname());
values.put(COLUMN_PASSWORD,r.getPassword());
values.put(COLUMN_RE_PASSWORD,r.getRe_password());
values.put(COLUMN_NAME,r.getName());
values.put(COLUMN_EMAIL, r.getEmail());
values.put(COLUMN_PHONE_NO, r.getPhone_no());
sqLiteDatabase.insert(TABLE_NAME, null,values); /*this will insert Register object in to the Database*/
sqLiteDatabase.close();
}
public String searchPass(String usr) {
sqLiteDatabase = this.getReadableDatabase();
String query = "select username,password from "+TABLE_NAME;
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
String a,b ; // a and b will be userName and Password respectively
b = "Not Found";
if (cursor.moveToFirst())
{
do {
a = cursor.getString(0);
Log.d("##username from db",a);
if (a.equals(usr))
{
b = cursor.getString(1);
break;
}
}while (cursor.moveToNext());
}
return b;
}
public JSONObject showDetail(String usr) {
sqLiteDatabase = this.getReadableDatabase();
String query ="SELECT * FROM registrations where username='"+usr+"'" ;//"select * from registrations where username = p";
// String query = "SELECT * FROM registrations";
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
JSONObject data = new JSONObject();
if (cursor.moveToFirst()){
do {
int columnsQty = cursor.getColumnCount();
Log.d("###count-->", String.valueOf(columnsQty));
for (int idx=0; idx<columnsQty; ++idx) {
try {
data.put(cursor.getColumnName(idx),cursor.getString(idx));
} catch (JSONException e) {
e.printStackTrace();
}
}
}while (cursor.moveToNext());
}
cursor.close();
Log.d("###Data Value",data.toString());
return data;
}
public void updateTable(Register r) {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_IMEI_NO,r.getImei_no());
Log.d("###Column_IMEI_NO",r.getImei_no());
cv.put(COLUMN_DEV_MODEL,r.getDev_model());
cv.put(COLUMN_OS_VERSION,r.getOs_version());
db.update(TABLE_NAME,cv,"username = ?",new String[]{r.getUname()});; /*Working for all fields*/
/*SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_IMEI_NO,r.getImei_no());
Log.d("###Column_IMEI_NO",r.getImei_no());
cv.put(COLUMN_DEV_MODEL,r.getDev_model());
cv.put(COLUMN_OS_VERSION,r.getOs_version());
String updateQuery = "Update registrations set " + COLUMN_IMEI_NO + " = '"+ r.getImei_no() +"' where " + COLUMN_USERNAME + "="+"'"+ r.getUname() +"'";
db.execSQL(updateQuery);
db.close();*/
}
}
//AdminDisplay.java
package com.example.yadapras.mobiltyemp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
public class AdminDisplay extends AppCompatActivity {
DatabaseHelper helper = new DatabaseHelper(this);
TextView id,name,email,mobileno,imei_no,dev_model ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.admin_display);
TableLayout table = (TableLayout)findViewById(R.id.tableLayout1) ;
id = (TextView)findViewById(R.id.admin_usr_id);
name = (TextView)findViewById(R.id.admin_Uname);
email = (TextView)findViewById(R.id.admin_usr_email);
mobileno = (TextView)findViewById(R.id.admin_usr_phone);
imei_no = (TextView)findViewById(R.id.admin_usr_imeiNo);
dev_model = (TextView)findViewById(R.id.admin_usr_dev_model);
JSONObject details = helper.showDetail("pcu9044"); // ***Here i'm trying registered user so i'm getting only this user field in TableLayout .***
for (int i=0; i<details.length();i++){
TableRow row = (TableRow)findViewById(R.id.tableRow1);
try {
table.removeView(row);
((TextView)row.findViewById(R.id.admin_usr_id)).setText(details.getString("id"));
((TextView)row.findViewById(R.id.admin_usr_email)).setText(details.getString("email"));
((TextView)row.findViewById(R.id.admin_Uname)).setText(details.getString("name"));
((TextView)row.findViewById(R.id.admin_usr_phone)).setText(details.getString("phone_no"));
((TextView)row.findViewById(R.id.admin_usr_imeiNo)).setText(details.getString("imei_no"));
((TextView)row.findViewById(R.id.admin_usr_dev_model)).setText(details.getString("dev_model"));
table.addView(row);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
i'm attaching screen shot of my output, if yup people have nay doubt please feel free to ask . Thank u in advance .
Result output with my code
The problem that I see here is that when you say:
"i try with specific user name and its showing in the table layout but
it's not my requirement , i have to show all users in Table layout".
By searching for one single user from the database, you are only retrieving a single record in the database that is associated with the username you are searching for. Your method helper.showDetail() returns a single JSONObject - this object corresponds to the record in the database where username = pcu9044.
If I am understanding your situation correctly, you need to call a method that selects ALL of the records from the database in order to display what you want on the screen. Your helper.showDetail() will be a good start, but you can modify code slightly to achieve what you'd like.
I would recommend using either a list or array of JSONObjects instead of a single JSONObject. Initialize your data structure before you enter the if (cursor.moveToFirst()) conditional (like you have it now), but within each iteration of the loop, you create a new object, fill it with what the cursor returns for that row, and then add it to the structure. The code would look something like this:
public JSONArray showDetail() {
sqLiteDatabase = this.getReadableDatabase();
String query ="SELECT * FROM registrations";// * THIS WILL RETURN ALL RECORDS IN REGISTRATIONS
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
//JSONObject data = new JSONObject(); *change this to an array
JSONArray data = new JSONArray();
if (cursor.moveToFirst()){
do {
int columnsQty = cursor.getColumnCount();
Log.d("###count-->", String.valueOf(columnsQty));
// Must create a new object each time you iterate to a new row to add to the array
JSONObject record = new JSONObject();
for (int idx=0; idx<columnsQty; ++idx) {
try {
// Fill the object
record.put(cursor.getColumnName(idx),cursor.getString(idx));
} catch (JSONException e) {
e.printStackTrace();
}
}
// Add the object to the array and repeat
data.put(record);
}while (cursor.moveToNext());
}
cursor.close();
Log.d("###Data Value",data.toString());
return data;
}
If you do it this way, your helper.showDetail() will return an array filled with objects that each symbolize a row. From there, your AdminDisplay.java should then cycle through the array, grab each object, and fill a new row with the information you need.
Hope this helps!
Hello Techie :) I solved my problem after reading many articles on Table Layout over Internet. i'm giving this problems solution with Table-Layout hope this will help others .
AdminDisplay.java # Editable Version
package com.example.yadapras.mobiltyemp;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.JsonReader;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
public class AdminDisplay extends AppCompatActivity {
TableLayout tableLayout;
private SQLiteDatabase db;
private Context context ;
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.admin_display);
context = this;
DatabaseHelper helper = new DatabaseHelper(this);
tableLayout = (TableLayout)findViewById(R.id.tableLayout1) ;
TableRow rowHeader = new TableRow(context);
rowHeader.setBackgroundColor(Color.parseColor("#c0c0c0"));
rowHeader.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
String[] headerText={"ID","USERNAME","EMAIL","PHONE_NO","IMEI_NO","DEV_MODEL"};
for(String c:headerText) {
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setGravity(Gravity.CENTER);
tv.setTextSize(18);
tv.setPadding(5, 5, 5, 5);
tv.setText(c);
rowHeader.addView(tv);
}
tableLayout.addView(rowHeader);
SQLiteDatabase db = helper.getReadableDatabase();
db.beginTransaction();
try
{
String selectQuery = "SELECT * FROM "+ DatabaseHelper.TABLE_NAME;
Cursor cursor = db.rawQuery(selectQuery,null);
if(cursor.getCount() >0)
{
while (cursor.moveToNext()) {
// Read columns data
int id = cursor.getInt(cursor.getColumnIndex("id"));
String user_name= cursor.getString(cursor.getColumnIndex("username"));
String email= cursor.getString(cursor.getColumnIndex("email"));
String phone_no = cursor.getString(cursor.getColumnIndex("phone_no"));
String imei_no = cursor.getString(cursor.getColumnIndex("imei_no"));
String dev_model = cursor.getString(cursor.getColumnIndex("dev_model"));
// dara rows
TableRow row = new TableRow(context);
row.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
String[] colText={id+"",user_name,email,phone_no,imei_no,dev_model};
for(String text:colText) {
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setGravity(Gravity.CENTER);
tv.setTextSize(16);
tv.setPadding(5, 5, 5, 5);
tv.setText(text);
row.addView(tv);
}
tableLayout.addView(row);
}
}
db.setTransactionSuccessful();
}
catch (SQLiteException e)
{
e.printStackTrace();
}
finally
{
db.endTransaction();
// End the transaction.
db.close();
// Close database
}
}
}
Remove table.removeView(row); from the loop, if not you will get only one row at the end of the loop as it removes the previous row when a new row is added
for (int i=0; i<details.length();i++){
TableRow row = (TableRow)findViewById(R.id.tableRow1);
try {
((TextView)row.findViewById(R.id.admin_usr_id)).setText(details.getString("id"));
((TextView)row.findViewById(R.id.admin_usr_email)).setText(details.getString("email"));
((TextView)row.findViewById(R.id.admin_Uname)).setText(details.getString("name"));
((TextView)row.findViewById(R.id.admin_usr_phone)).setText(details.getString("phone_no"));
((TextView)row.findViewById(R.id.admin_usr_imeiNo)).setText(details.getString("imei_no"));
((TextView)row.findViewById(R.id.admin_usr_dev_model)).setText(details.getString("dev_model"));
table.addView(row);
} catch (JSONException e) {
e.printStackTrace();
}
}
Hi try this method i have just updated a method of your code, You can replace with your own method by.
Valiable isAdmin is true when admin get detail and false when user.
public JSONObject showDetail(String usr, boolean isAdmin)
{
sqLiteDatabase = this.getReadableDatabase();
String query = "";
if (isAdmin)
query = "SELECT * FROM registrations";
else
query ="SELECT * FROM registrations where username='"+usr+"'" ;//"select * from registrations where username = p";
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
JSONObject data = new JSONObject();
if (cursor.moveToFirst()){
do {
int columnsQty = cursor.getColumnCount();
Log.d("###count-->", String.valueOf(columnsQty));
for (int idx=0; idx<columnsQty; ++idx) {
try {
data.put(cursor.getColumnName(idx),cursor.getString(idx));
} catch (JSONException e) {
e.printStackTrace();
}
}
}while (cursor.moveToNext());
}
cursor.close();
Log.d("###Data Value",data.toString());
return data;
}
It may help you and Let me know if any query you have.
I wonder if someone could show me the error of my ways--I've been struggling with this issue for two days, and realize it must be a fundamental error of initializing variables, but...that reflects the level of my java knowledge.
I'm getting a database result on a delimited string wherein each of the segments has "null" appended to it. It seems that no matter how I change the initialization...well, two days!
I'm declaring the following in the class heading area:
private String strListContent;
private SQLiteDatabase database;
private DatabaseHelper helper2 = new DatabaseHelper(this);
private static final String fields[] = { "_id", "listTitle", "listType",
"listContent", "dateCreated", "dateModified" };
private ArrayList<String> textArray = new ArrayList<String>();
private ArrayList<Integer> imageArray = new ArrayList<Integer>();
Then concatenating my items in
final ImageButton addItem = (ImageButton) findViewById(R.id.btnToAddItem);
addItem.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
itemEdit = (EditText) findViewById(R.id.editTextItem);
if (itemEdit.getText().toString().equals("")) {
showToastMessage("Please enter an item to add...");
} else {
String newListItem = itemEdit.getText().toString();
strListContent += newListItem + "|~|";
...
}}}
I'm using the following bare-bones SQLiteOpenHelper:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String KEY_ID = "_id";
public DatabaseHelper(Context context) {
super(context, "Cursor", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS list_data ("
+ KEY_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, listTitle TEXT, listType TEXT, listContent TEXT, dateCreated TEXT, dateModified TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Steps to upgrade the database for the new version ...
}
}
To insert the values as so:
ImageButton saveAndBack = (ImageButton) findViewById(R.id.btnSaveBack);
saveAndBack.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String title = null;
String listContent = null;
Calendar javaCalendar = null;
title = titleEdit.getText().toString();
title = (title=="" || title==null)?"Untitled List":title;
strListContent = (strListContent=="" || strListContent==null)?"No Items|~|":strListContent;
listContent = strListContent;
String type = "R"; //"Regular List"
javaCalendar = Calendar.getInstance();
String currentDate = javaCalendar.get(Calendar.MONTH) + "/" + (javaCalendar.get(Calendar.DATE) + 1) + "/" + javaCalendar.get(Calendar.YEAR);
database = helper2.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("listTitle", title);
values.put("listType", type);
values.put("listContent", listContent);
values.put("dateCreated", currentDate);
values.put("dateModified", currentDate);
database.insert("list_data", null, values);
Intent i = new Intent(RegularList.this, ActivityMain.class);
startActivity(i);
}
});
}
//
//End of OnCreate(){}
//
Then, when I retrieve from another activity:
DatabaseHelper helper = new DatabaseHelper(this);
database = helper.getWritableDatabase();
Cursor data = database.query("list_data", fields, null, null, null,
null, null);
Integer tindex = data.getColumnIndex("listTitle");
Integer iindex = data.getColumnIndex("listType");
Integer cindex = data.getColumnIndex("listContent");
itemCount = 0;
for (data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
showToastMessage(data.getString(cindex));
titleArrayList.add(data.getString(tindex));
if (data.getString(iindex) == "R") {
imageArrayList.add(R.drawable.listview_regular);
} else if (data.getString(iindex) == "L") {
imageArrayList.add(R.drawable.listview_location);
} else {
imageArrayList.add(R.drawable.listview_regular);
}
itemCount++;
}
data.close();
...
I can see in the toast message that each item from the delimited string has "null" appended to the front of it...the other values are fine. I hope this hasn't been too verbose, but...any recommendations? Thanks!
To me it looks like you may have simply not initialised the String strListContent before you first append to it with:
strListContent += newListItem + "|~|";
When you do that, you'll get a "null" prefixed in front of the value you are trying to append, just as you observe.
Perhaps you can just initialise in the declaration:
private String strListContent = "";