SimpleCursorAdapter not populating a ListView - android

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".

Related

Unable to calculate total price amount in cart using sqlite

I wanted to calculate the total price of the products in the cart using SQLite. When I set the price in textview using Settext(), it does not return the sum value. This is the gettotalprice method in DBhelper class.
public int getTotalExpenses()
{
int total = 0;
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor = database.rawQuery("SELECT SUM("+ OrderContract.OrderEntry.COLUMN_PRICE + ") FROM " + OrderContract.OrderEntry.TABLE_NAME, null);
if (cursor.moveToFirst())
{
total = cursor.getInt(4);
}
while (cursor.moveToNext());
return total;
}
OrderProvider class:
package com.example.myapp;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class OrderProvider extends ContentProvider {
// this constant is needed in order to define the path of our modification in the table
public static final int ORDER=100;
public DBHelper mhelper;
public static UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sUriMatcher.addURI(OrderContract.CONTENT_AUTHORITY,OrderContract.PATH,ORDER);
}
#Override
public boolean onCreate() {
mhelper = new DBHelper(getContext());
return true;
}
#Override
public Cursor query( Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase database = mhelper.getReadableDatabase();
Cursor cursor;
int match = sUriMatcher.match(uri);
switch (match){
case ORDER:
cursor = database.query(OrderContract.OrderEntry.TABLE_NAME, projection, selection, selectionArgs, null,null, sortOrder);
break;
default:
throw new IllegalArgumentException("CANT QUERY");
}
cursor.setNotificationUri(getContext().getContentResolver(),uri);
return cursor;
}
#Override
public String getType(Uri uri) {
return null;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
int match = sUriMatcher.match(uri);
switch (match) {
case ORDER:
return insertCart(uri, values);
default:
throw new IllegalArgumentException("Cant insert data");
}
}
private Uri insertCart(Uri uri, ContentValues values) {
String name = values.getAsString(OrderContract.OrderEntry.COLUMN_NAME);
if(name == null){
throw new IllegalArgumentException("Name is Required");
}
String quantity = values.getAsString(OrderContract.OrderEntry.COLUMN_QUANTITY);
if(quantity == null){
throw new IllegalArgumentException("Quantity is Required");
}
String price = values.getAsString(OrderContract.OrderEntry.COLUMN_PRICE);
if(price == null){
throw new IllegalArgumentException("Price is Required");
}
//insert values into order
SQLiteDatabase database = mhelper.getWritableDatabase();
long id = database.insert(OrderContract.OrderEntry.TABLE_NAME, null, values);
if(id == 0){
return null;
}
getContext().getContentResolver().notifyChange(uri,null);
return ContentUris.withAppendedId(uri,id);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
//delete data once order is made
int rowsDeleted;
SQLiteDatabase database = mhelper.getWritableDatabase();
int match = sUriMatcher.match(uri);
switch (match) {
case ORDER:
rowsDeleted = database.delete(OrderContract.OrderEntry.TABLE_NAME, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Cannot delete");
}
if (rowsDeleted!=0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return rowsDeleted;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
OrderContract class:
public class OrderContract {
public OrderContract() {
}
//content authority requires package name
public static final String CONTENT_AUTHORITY = "com.example.myapp";
public static final Uri BASE_URI = Uri.parse(("content://" +CONTENT_AUTHORITY));
//same as table name
public static final String PATH = "orders" ;
public static abstract class OrderEntry implements BaseColumns{
public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_URI,PATH);
public static final String TABLE_NAME = "orders" ;
public static final String _ID = BaseColumns._ID ;
public static final String COLUMN_NAME = "name" ;
public static final String COLUMN_QUANTITY = "quantity" ;
public static final String COLUMN_PRICE = "price" ;
}
}
Cart activity:
sofaname=findViewById(R.id.sofaname);
sofaprice=findViewById(R.id.sofaprice);
sofadesc=findViewById(R.id.sofadesc);
plusquantity = findViewById(R.id.addquantity);
minusquantity = findViewById(R.id.subquantity);
quantitynumber = findViewById(R.id.quantity);
addtocart = findViewById(R.id.addtocart);
ImageSlider imageSlider = findViewById(R.id.sofaslider1);
List<SlideModel> slideModels = new ArrayList<>();
slideModels.add(new SlideModel(R.drawable.card14));
slideModels.add(new SlideModel(R.drawable.card6));
slideModels.add(new SlideModel(R.drawable.card7));
imageSlider.setImageList(slideModels,false);
imageSlider.setClickable(false);
DB = new DBHelper(Sofa1.this);
String Name = DB.getProductNamePrice("SELECT F_Name FROM Furniture WHERE F_Type = 'Sofa';");
String Price = DB.getProductNamePrice("SELECT F_Price FROM Furniture WHERE F_Type = 'Sofa';");
String Desc = DB.getProductNamePrice("SELECT F_Description FROM Furniture WHERE F_Type = 'Sofa';");
sofaname.setText(Name);
sofaprice.setText(Price);
sofadesc.setText(Desc);
plusquantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(quantity<5){
//sofaprice
int baseprice= Integer.parseInt(sofaprice.getText().toString());
quantity++;
displayquantity();
totalprice = baseprice * quantity;
String setnewprice = (String.valueOf(totalprice));
sofaprice.setText(setnewprice);
}
}
});
minusquantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int baseprice=0;
String Price = DB.getProductNamePrice("SELECT F_Price FROM Furniture WHERE F_Type = 'Sofa';");
baseprice = Integer.parseInt(Price);
if(quantity>1) {
quantity--;
displayquantity();
totalprice = baseprice * quantity;
String setnewprice = (String.valueOf(totalprice));
sofaprice.setText(setnewprice);
}
}
});
addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent =new Intent(Sofa1.this,Cart.class);
startActivity(intent);
// once this button is clicked we want to save our values in the database and send those values
// right away to summary activity where we display the order info
SaveCart();
totalamount = (TextView) findViewById(R.id.total);
int totalAmount = DB.getTotalExpenses();
totalamount.setText(String.valueOf(totalAmount));
}
});
}
private boolean SaveCart() {
String name = sofaname.getText().toString();
String price = sofaprice.getText().toString();
String quantity = quantitynumber.getText().toString();
ContentValues values = new ContentValues();
values.put(OrderContract.OrderEntry.COLUMN_NAME,name);
values.put(OrderContract.OrderEntry.COLUMN_PRICE,price);
values.put(OrderContract.OrderEntry.COLUMN_QUANTITY,quantity);
if(mcurrentcarturi == null){
Uri newUri = getContentResolver().insert(OrderContract.OrderEntry.CONTENT_URI, values);
if(newUri == null){
Toast.makeText(this, "Failed to add to cart", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Product added to cart", Toast.LENGTH_SHORT).show();
}
}
hasallrequiredvalues = true;
return hasallrequiredvalues;
}
private void displayquantity() {
quantitynumber.setText(String.valueOf(quantity));
}
#Override
public #NotNull Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {OrderContract.OrderEntry._ID,
OrderContract.OrderEntry.COLUMN_NAME,
OrderContract.OrderEntry.COLUMN_PRICE,
OrderContract.OrderEntry.COLUMN_QUANTITY};
return new CursorLoader(this, mcurrentcarturi, projection, null, null, null);
}
#Override
public void onLoadFinished(#NotNull Loader<Cursor> loader, Cursor cursor) {
if(cursor==null || cursor.getCount() < 1){
return;
}
if(cursor.moveToFirst()){
int name = cursor.getColumnIndex(OrderContract.OrderEntry.COLUMN_NAME);
int price = cursor.getColumnIndex(OrderContract.OrderEntry.COLUMN_PRICE);
int quantity = cursor.getColumnIndex(OrderContract.OrderEntry.COLUMN_QUANTITY);
String nameofsofa = cursor.getString(name);
String priceofsofa = cursor.getString(price);
String quantityofsofa = cursor.getString(quantity);
sofaname.setText(nameofsofa);
sofaprice.setText(priceofsofa);
quantitynumber.setText(quantityofsofa);
}
}
#Override
public void onLoaderReset(#NotNull Loader<Cursor> loader) {
sofaname.setText("");
sofaprice.setText("");
quantitynumber.setText("");
}
As your query is effectively
SELECT SUM(price) FROM orders;
Only a single column will be returned, thus using total = cursor.getInt(4); should result in an exception as the column is out of bounds, there will only be 1 column and it's index will be 0.
Thus try changing to use :-
public int getTotalExpenses()
{
int total = 0;
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor = database.rawQuery("SELECT SUM("+ OrderContract.OrderEntry.COLUMN_PRICE + ") FROM " + OrderContract.OrderEntry.TABLE_NAME, null);
if (cursor.moveToFirst())
{
total = cursor.getInt(0); //<<<<<<<<<< CHANGED
}
//while (cursor.moveToNext()); //<<<<<<<<<< COMMENTED OUT NOT NEEDED
cursor.close(); //<<<<<<<<<< ADDED should always close cursor when finished with them
return total;
}

how I can change the value of the button depending on Spinner which takes the data from the database in Android?

I have a project to do android app, my app is about movies, I used the spinner to choose the name of the movie and there is a trailer button for each movie.
my question is how I can change the value of the button depending on the name of the movie.
I hope my question was clear
MainActivity class
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
TextView director;
TextView year;
TextView genre;
ImageView imageView;
TextView rating;
Button trailer;
TextView movieStory;
String[] movieNames = {"Test"};
Spinner movieSpinner;
movieDB MovieDB;
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
movieSpinner = (Spinner) findViewById(R.id.moviespinner);
trailer = (Button) findViewById(R.id.button);
MovieDB = new movieDB(getApplicationContext());
rating = (TextView) findViewById(R.id.rateText);
director = (TextView) findViewById(R.id.director);
year = (TextView) findViewById(R.id.year);
genre = (TextView) findViewById(R.id.genretext);
imageView = (ImageView) findViewById(R.id.imageView);
movieStory = (TextView) findViewById(R.id.movieDetails);
movieNames = MovieDB.getMovieNames();
ArrayAdapter<String> movieAdapter = new ArrayAdapter<String>(getBaseContext(), R.layout.list_movie, movieNames);
movieAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
movieSpinner.setAdapter(movieAdapter);
movieSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
final int position, long arg3) {
if (movieNames.length > position) {
director.setText(MovieDB.getDirector(movieNames[position]));
year.setText(MovieDB.getYear(movieNames[position]).toString());
genre.setText(MovieDB.getGenre(movieNames[position]));
imageView.setImageResource(MovieDB.getPhoto(movieNames[position]));
rating.setText(((Float) MovieDB.getRate(movieNames[position])).toString());
movieStory.setText(MovieDB.getStory(movieNames[position]));
// here is the trailer button
trailer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent webIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.youtube.com/watch?v=gZjQROMAh_s"));
try {
MainActivity.this.startActivity(webIntent);
} catch (ActivityNotFoundException ex) {
}
}
});
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
the database
movieDB class
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
public class movieDB {
public static final String KEY_ID = "_id";
public static final String KEY_MOVIE_NAME =
"movie_name";
public static final String KEY_DIRECTOR =
"director_name";
public static final String KEY_YEAR =
"year";
public static final String KEY_GENRE =
"genre";
public static final String KEY_PHOTO =
"pic";
public static final String KEY_RATE =
"rate";
public static final String KEY_STORY =
"story";
public static final String KEY_URL =
"url";
private Context context;
private ModuleDBOpenHelper moduleDBOpenHelper;
public movieDB(Context context) {
this.context = context;
moduleDBOpenHelper = new ModuleDBOpenHelper(context, ModuleDBOpenHelper.DATABASE_NAME, null,
ModuleDBOpenHelper.DATABASE_VERSION);
// populate the database with some data in case it is empty
if (getAll().length == 0) {
this.addRow("1917", "Todd Phillips", 2019 ,"Crime, Drama, Thriller" , R.mipmap.mov_1917_foreground, 8.4f , context.getString(R.string.mov1917story),"https://www.youtube.com/watch?v=gZjQROMAh_s");
this.addRow("Avatar", "James Cameron", 2009, "Action, Adventure, Fantasy, Sci-Fi" , R.mipmap.avatar_foreground , 7.8f , context.getString(R.string.avatarstory),"https://www.youtube.com/watch?v=5PSNL1qE6VY");
this.addRow("Joker", "Todd Phillips", 2019,"Crime, Drama, Thriller" , R.mipmap.joker_foreground , 8.6f, context.getString(R.string.jokerstory),"https://www.youtube.com/watch?v=zAGVQLHvwOY");
this.addRow("Once Upon a Time in Hollywood", "Vladislav Kozlov", 2019,"Drama" , R.mipmap.hollywood_foreground , 7.7f , context.getString(R.string.hollywoodstory),"https://www.youtube.com/watch?v=ELeMaP8EPAA");
this.addRow("The Irishman", "Martin Scorsese", 2019,"Biography, Crime, Drama" , R.mipmap.irish_foreground , 8.0f , context.getString(R.string.irishmanstory),"https://www.youtube.com/watch?v=RS3aHkkfuEI");
}
}
public void addRow(String movieName, String director, int year, String genre , int pic , float rate , String story , String url) {
// Create a new row of values to insert.
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(KEY_MOVIE_NAME, movieName);
newValues.put(KEY_DIRECTOR, director);
newValues.put(KEY_YEAR, year);
newValues.put(KEY_GENRE, genre);
newValues.put(KEY_PHOTO, pic);
newValues.put(KEY_RATE, rate);
newValues.put(KEY_STORY, story);
newValues.put(KEY_URL, url);
// Insert the row into your table
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
db.insert(ModuleDBOpenHelper.DATABASE_TABLE, null, newValues);
}
public String[] getAll() {
ArrayList<String> outputArray = new ArrayList<String>();
String[] result_columns = new String[]{
KEY_MOVIE_NAME, KEY_DIRECTOR, KEY_YEAR , KEY_GENRE};
String movieName;
String directorName;
int year;
String genre;
String where = null;
String whereArgs[] = null;
String groupBy = null;
String having = null;
String order = null;
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(ModuleDBOpenHelper.DATABASE_TABLE,
result_columns, where,
whereArgs, groupBy, having, order);
boolean result = cursor.moveToFirst();
while (result) {
movieName = cursor.getString(cursor.getColumnIndex(KEY_MOVIE_NAME));
directorName = cursor.getString(cursor.getColumnIndex(KEY_DIRECTOR));
year = cursor.getInt(cursor.getColumnIndex(KEY_YEAR));
genre = cursor.getString(cursor.getColumnIndex(KEY_GENRE));
outputArray.add(movieName + " "+ directorName + year + " " + genre);
result = cursor.moveToNext();
}
return outputArray.toArray(new String[outputArray.size()]);
}
public String[] getMovieNames() {
ArrayList<String> outputArray = new ArrayList<String>();
String[] result_columns = new String[]{
KEY_MOVIE_NAME};
String movieName;
String where = null;
String whereArgs[] = null;
String groupBy = null;
String having = null;
String order = null;
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(ModuleDBOpenHelper.DATABASE_TABLE,
result_columns, where,
whereArgs, groupBy, having, order);
//
boolean result = cursor.moveToFirst();
while (result) {
movieName = cursor.getString(cursor.getColumnIndex(KEY_MOVIE_NAME));
outputArray.add(movieName);
result = cursor.moveToNext();
}
return outputArray.toArray(new String[outputArray.size()]);
}
public String geturl(String movieName) {
String[] result_columns = new String[]{
KEY_ID, KEY_URL};
String where = KEY_MOVIE_NAME + "= ?";
String whereArgs[] = {movieName};
String groupBy = null;
String having = null;
String order = null;
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(ModuleDBOpenHelper.DATABASE_TABLE,
result_columns, where,
whereArgs, groupBy, having, order);
if (cursor.moveToFirst()) {
int columnGenre = cursor.getColumnIndex(KEY_URL);
return cursor.getString(columnGenre);
} else return null;
}
public Integer getYear(String movieName) {
String[] result_columns = new String[]{
KEY_ID, KEY_YEAR};
String where = KEY_MOVIE_NAME + "= ?";
String whereArgs[] = {movieName};
String groupBy = null;
String having = null;
String order = null;
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(ModuleDBOpenHelper.DATABASE_TABLE,
result_columns, where,
whereArgs, groupBy, having, order);
if (cursor.moveToFirst()) {
int columnYear = cursor.getColumnIndex(KEY_YEAR);
return cursor.getInt(columnYear);
} else return 0;
}
public String getGenre(String movieName) {
String[] result_columns = new String[]{
KEY_ID, KEY_GENRE};
String where = KEY_MOVIE_NAME + "= ?";
String whereArgs[] = {movieName};
String groupBy = null;
String having = null;
String order = null;
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(ModuleDBOpenHelper.DATABASE_TABLE,
result_columns, where,
whereArgs, groupBy, having, order);
if (cursor.moveToFirst()) {
int columnGenre = cursor.getColumnIndex(KEY_GENRE);
return cursor.getString(columnGenre);
} else return null;
}
public String getStory(String movieName) {
String[] result_columns = new String[]{
KEY_ID, KEY_STORY};
String where = KEY_MOVIE_NAME + "= ?";
String whereArgs[] = {movieName};
String groupBy = null;
String having = null;
String order = null;
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(ModuleDBOpenHelper.DATABASE_TABLE,
result_columns, where,
whereArgs, groupBy, having, order);
if (cursor.moveToFirst()) {
int columnStory = cursor.getColumnIndex(KEY_STORY);
return cursor.getString(columnStory);
} else return null;
}
public Integer getPhoto(String movieName) {
String[] result_columns = new String[]{
KEY_ID, KEY_PHOTO};
String where = KEY_MOVIE_NAME + "= ?";
String whereArgs[] = {movieName};
String groupBy = null;
String having = null;
String order = null;
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(ModuleDBOpenHelper.DATABASE_TABLE,
result_columns, where,
whereArgs, groupBy, having, order);
if (cursor.moveToFirst()) {
int columnPhoto = cursor.getColumnIndex(KEY_PHOTO);
return cursor.getInt(columnPhoto);
} else return 0;
}
public float getRate(String movieName) {
String[] result_columns = new String[]{
KEY_ID, KEY_RATE};
String where = KEY_MOVIE_NAME + "= ?";
String whereArgs[] = {movieName};
String groupBy = null;
String having = null;
String order = null;
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(ModuleDBOpenHelper.DATABASE_TABLE,
result_columns, where,
whereArgs, groupBy, having, order);
if (cursor.moveToFirst()) {
int columnRate = cursor.getColumnIndex(KEY_RATE);
return cursor.getFloat(columnRate);
} else return 0;
}
public String getDirector(String movieName) {
String[] result_columns = new String[]{
KEY_ID, KEY_DIRECTOR};
String where = KEY_MOVIE_NAME + "= ?";
String whereArgs[] = {movieName};
String groupBy = null;
String having = null;
String order = null;
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(ModuleDBOpenHelper.DATABASE_TABLE,
result_columns, where,
whereArgs, groupBy, having, order);
if (cursor.moveToFirst()) {
int columnDirector = cursor.getColumnIndex(KEY_DIRECTOR);
return cursor.getString(columnDirector);
} else return null;
}
private static class ModuleDBOpenHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "myDatabase.db";
private static final String DATABASE_TABLE = "Movies";
private static final int DATABASE_VERSION = 1;
// SQL Statement to create a new database.
private static final String DATABASE_CREATE = "create table " +
DATABASE_TABLE + " (" + KEY_ID +
" integer primary key autoincrement, " +
KEY_MOVIE_NAME + " text not null, " +
KEY_DIRECTOR + " text , " +
KEY_YEAR + " int , " +
KEY_GENRE + " text , " +
KEY_PHOTO + " int , " +
KEY_RATE + " float , " +
KEY_STORY + " text , " +
KEY_URL + " text );";
public ModuleDBOpenHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
// Called when there is a database version mismatch meaning that
// the version of the database on disk needs to be upgraded to
// the current version.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +
oldVersion + " to " +
newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new
// version. Multiple previous versions can be handled by
// comparing oldVersion and newVersion values.
// The simplest case is to drop the old table and create a new one.
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Create a new one.
onCreate(db);
}
}
}
XML Layout
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Spinner
android:id="#+id/moviespinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"/>
<RelativeLayout
android:id="#+id/directorcontainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/moviespinner">
<TextView
android:id="#+id/directorHeading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="#string/director"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceSmall"/>
<TextView
android:id="#+id/director"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#+id/directorHeading"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/yearcontainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/directorcontainer"
android:layout_toRightOf="#+id/directorcontainer"
android:layout_marginLeft="20dp"
android:layout_toEndOf="#+id/directorcontainer"
android:layout_marginStart="20dp">
<TextView
android:id="#+id/yearHeading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="#string/year"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceSmall"/>
<TextView
android:id="#+id/year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#+id/yearHeading"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/genrecontainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/directorcontainer"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#id/yearcontainer"
android:layout_marginStart="20dp"
android:layout_toEndOf="#id/yearcontainer">
<TextView
android:id="#+id/genreHeading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="#string/genre"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/genretext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/genreHeading"
android:layout_centerHorizontal="true" />
</RelativeLayout>
<LinearLayout
android:layout_below="#+id/genrecontainer"
android:layout_width="match_parent"
android:layout_height="661dp"
android:layout_alignParentBottom="true"
android:layout_marginTop="8dp"
android:layout_marginBottom="0dp"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="147dp"
android:contentDescription="#string/thumb"
app:srcCompat="#drawable/ic_launcher_background" />
<Space
android:layout_width="match_parent"
android:layout_height="20dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="70dp"
android:orientation="horizontal">
<Button
android:id="#+id/button"
style="#android:style/Widget.Button.Inset"
android:layout_width="98dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="#string/trailer" />
<Space
android:layout_width="34dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<LinearLayout
android:layout_width="34dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical">
<Space
android:layout_width="match_parent"
android:layout_height="20dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/star"
android:layout_width="45dp"
android:layout_height="wrap_content"
android:contentDescription="#string/app_name"
app:srcCompat="#android:drawable/btn_star_big_on" />
<TextView
android:id="#+id/rateText"
android:layout_width="35dp"
android:layout_height="match_parent"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="#+id/rate10"
android:layout_width="0dp"
android:layout_height="20dp"
android:layout_marginTop="5dp"
android:layout_weight="1"
android:text="#string/_10" />
</LinearLayout>
<Space
android:layout_width="match_parent"
android:layout_height="13dp" />
</LinearLayout>
</LinearLayout>
<TextView
android:id="#+id/movieDetails"
android:layout_width="match_parent"
android:layout_height="180dp" />
<Space
android:layout_width="match_parent"
android:layout_height="50dp" />
<TextView
android:id="#+id/test_URL"
android:layout_width="match_parent"
android:layout_height="90dp" />
</LinearLayout>
</RelativeLayout>
XML Layout list_movie.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
[Image] the appearance of the application
Thanks in advance
Try this:
trailer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent webIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(MovieDB.geturl(movieNames[position])));
try {
MainActivity.this.startActivity(webIntent);
} catch (ActivityNotFoundException ex) {
}
}
});

Populating data from Edittext input to Spinner Display using Sqlite

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

Why getView not getting called? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have an adapter that extends simplecursoradapter. For some reason I can't seem to see, my getView is not even being called. I have a breakpoint inside getView and it never gets there and the list just shows up empty. Can anyone take a look thru and see what I've done wrong?
package com.example.ok1;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.app.ListActivity;
public class MainActivity extends Activity {
// Button btnCalendar;
//*******************************************8
String[] names = {"Иван", "Марья", "Петр", "Антон", "Даша", "Борис",
"Костя", "Игорь", "Анна", "Денис", "Андрей"};
//Button buttonAddTask;
final String Tag="States";
final String Ten = "Ten";
TextView txtDataTaskToday;
String id_for_listtsk_today;
ListView lvMain_today;
String[] arr_date;
SharedPreferences sPref;
static Cursor c;
private ListView listView = null;
//public static String id_for_listtsk_today;
// static SQLiteDatabase db;
MySqlCursorAdapter adapter = null;
//***********************************************8
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// btnCalendar = (Button) findViewById(R.id.btnActTwo);
// btnCalendar.setOnClickListener(this);
//*********************************************
// переменные для query
String[] columns = null;
String selection = null;
String[] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
//*********работа с БД****************
// создаем объект для данных
// txtDataTaskToday = (TextView) findViewById(R.id.txtDataTaskToday);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String id_for_listtsk_today = sdf.format(new Date());
//final String b = id_for_listtsk_today;
// txtDataTaskToday.setText(id_for_listtsk_today.toString());
Log.d(Tag, "id_for_listtsk_today ="+id_for_listtsk_today );
ContentValues cv = new ContentValues();
DBHelper dbHelper = new DBHelper(this);
final SQLiteDatabase db = dbHelper.getWritableDatabase();
columns = new String[] {"name"};
selection = "data_id = ?";
selectionArgs = new String[] {id_for_listtsk_today};
//c = db.query("mytable", columns, selection, selectionArgs, null, null, null);
try {
c=dbHelper.getCursor();
} catch (SQLException sqle) {
Log.d(Tag, "неудача");
throw sqle;
}
String[] arr_date = logCursor(c);
//*********работа с БД****************
lvMain_today = (ListView) findViewById(R.id.list);
// lvMain_today.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//this.listView=getl
//listView = MainActivity.this.getlgetListView();
lvMain_today.setItemsCanFocus(false);
lvMain_today.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, arr_date);// R.layout.item, my_list_item
startManagingCursor(c);
int[] listFields = new int[] { R.id.txtTitle };
String[] dbColumns = new String[] { DBHelper.COLUMN_NAME };
Log.d(Tag, "трассировка" );
MainActivity.this.adapter = new MySqlCursorAdapter(
this, R.layout.my_list_item,
c, dbColumns, listFields,
dbHelper);
//
lvMain_today.setAdapter(MainActivity.this.adapter);
// setListAdapter(MainActivity.this.adapter);
names = arr_date;
c.close();
db.close();
dbHelper.close();
lvMain_today.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
SparseBooleanArray chosen = ((ListView) parent).getCheckedItemPositions();
for (int i = 0; i < chosen.size(); i++) {
int key = chosen.keyAt(i);
if (chosen.get(key))
Log.d(Tag, "выделены ====="+names[key]);
Log.d(Tag, "itemClick: position = " + position + ", id = "
+ id);}
//****************nen пробная фигня**************
// String[] columns = null;
// String selection = null;
// String[] selectionArgs = null;
// String groupBy = null;
// String having = null;
// String orderBy = null;
// columns = new String[] {"name"};
// selection = "data_id = ?";
// selectionArgs = new String[] {id_for_listtsk_today};//id_for_listtsk_today
// Cursor c = db.query("mytable", columns, selection, selectionArgs, null, null, null);
// String[] arr = logCursor(c);
//**************************************************
// String s=test();
}
});
// lvMain_today.setOnItemSelectedListener(new OnItemSelectedListener() {
// public void onItemSelected(AdapterView<?> parent, View view,
// int position, long id) {
// Log.d(Tag, "Было выделение позиции меню!!!!position = " + position + ", id = "
// + id);
// }
//
// public void onNothingSelected(AdapterView<?> parent) {
// Log.d(Tag, "itemSelect: nothing");
// }
// });
}
private String[] logCursor(Cursor c) {
// TODO Auto-generated method stub
final String Tag="States";
String[] arr_date = new String[c.getCount()];//String[] arr_date = new String[] {};
Log.d(Tag,"мы в курсоре");
if (c!=null) {
if (c.moveToFirst()) {
// Log.d(Tag,"мы в курсоре1");
String str;
int i=-1;
do {
// Log.d(Tag,"мы в курсоре2");
str="";
i=i+1;
for (String cn: c.getColumnNames()) {
str = str.concat(c.getString(c.getColumnIndex(cn)));
}
Log.d(Tag, "++++"+str);
arr_date[i]=String.valueOf(str);
} while (c.moveToNext());
}
}
return arr_date;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menu.add(0, 1, 0, "календарь");
menu.add(0, 2, 0, "Убрать выполненные");
menu.add(0, 3, 3, "Уйти");
// menu.add(1, 4, 1, "copy");
// menu.add(1, 5, 2, "paste");
// menu.add(1, 6, 4, "exit");
return super.onCreateOptionsMenu(menu);
// getMenuInflater().inflate(R.menu.main, menu);
//return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
// Выведем в TextView информацию о нажатом пункте меню
// txtDataTaskToday.setText("Item Menu");
// txtDataTaskToday.setText(item.getGroupId());
//// txtDataTaskToday.setText("\r\n itemId: " + String.valueOf(item.getItemId()));
// txtDataTaskToday.setText("\r\n order: " + String.valueOf(item.getOrder()));
// txtDataTaskToday.setText("\r\n title: " + item.getTitle());
switch (item.getItemId()) {
case 1:
Intent intent = new Intent(this, ToDoCalendarActivity.class);
startActivity(intent);
break;
case 2:
SparseBooleanArray sbArray = lvMain_today.getCheckedItemPositions();
for (int i = 0; i < sbArray.size(); i++) {
int key = sbArray.keyAt(i);
if (sbArray.get(key))
Log.d(Tag, "выделены "+names[key]);
sPref = getPreferences(MODE_PRIVATE);
Editor ed = sPref.edit();
ed.putString(Ten, "1");
ed.commit();
Log.d(Tag, "ставим константу для скрытия");
}
break;
case 3:
sPref = getPreferences(MODE_PRIVATE);
String savedText = sPref.getString(Ten, "");
Log.d(Tag, "ten= "+ savedText);
finish();
break;
}
return super.onOptionsItemSelected(item);
}
// #Override
// public void onClick(View v) {
// // TODO Auto-generated method stub
// switch (v.getId()) {
// case R.id.btnActTwo:
//
// Intent intent = new Intent(this, ToDoCalendarActivity.class);
// startActivity(intent);
// break;
// }
// }
}
MySqlCursorAdapter
package com.example.ok1;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class MySqlCursorAdapter extends SimpleCursorAdapter implements OnClickListener {
final String Tag="States";
private Context context;
private DBHelper dbHelper;
private Cursor currentCursor;
public MySqlCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, DBHelper dbHelper) {
super(context, layout, c, from, to);
Log.d(Tag, "трассировка1" );
this.currentCursor = c;
this.context = context;
this.dbHelper = dbHelper;
Log.d(Tag, "MySqlCursorAdapter()");
Integer b = c.getCount();
Log.d(Tag, "b="+b);
}
public View getView(int pos, View inView, ViewGroup parent) {
Log.d(Tag, "getView() + posss=" + pos);
View v = inView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.my_list_item, null);
}
this.currentCursor.moveToPosition(pos);
CheckBox cBox = (CheckBox) v.findViewById(R.id.bcheck);
cBox.setTag(Integer.parseInt(this.currentCursor
.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_ID))));
Log.d(Tag, "tag="+cBox.getTag().toString());
if (this.currentCursor.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_STATUS)) != null
&& Integer.parseInt(this.currentCursor
.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_STATUS))) != 0) {
cBox.setChecked(true);
} else {
cBox.setChecked(false);
}
cBox.setOnClickListener(this);
TextView txtTitle = (TextView) v.findViewById(R.id.txtTitle);
txtTitle.setText(this.currentCursor.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_NAME)));
return (v);
}
public void ClearSelections() {
Log.d(Tag, "ClearSelections()");
//this.dbHelper.clearSelections();
//this.currentCursor.requery();
}
#Override
public void onClick(View v) {
Log.d(Tag, "onClick");
CheckBox cBox = (CheckBox) v;
Integer _id = (Integer) cBox.getTag();
Log.d(Tag, "Integer _id="+_id.toString());
ContentValues values = new ContentValues();
values.put(" selected", cBox.isChecked() ? 1 : 0);
//this.dbHelper.dbSqlite.update(SqlHelper.TABLE_NAME, values, "_id=?",
// new String[] { Integer.toString(_id) });
}
}
DBHelper
package com.example.ok1;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.util.Log;
public class DBHelper extends SQLiteOpenHelper {
final String Tag="States";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_DATA = "data_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_STATUS = "status";
public static final String TABLE_NAME = "mytable";
public SQLiteDatabase dbSqlite;
public DBHelper(Context context) {
// конструктор суперкласса
super(context, "myDB", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d(Tag, "--- onCreate database ---");
// создаем таблицу с полями
db.execSQL("create table mytable ("
+ "_id integer primary key autoincrement,"
+ "data_id text,"
+ "name text,"
+ "task text,"
+ "status integer"
+ ");");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor getCursor() {
Log.d(Tag, "getCursor() получили курсор с базы");
String[] columns = null;
String selection = null;
String[] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
// SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
// queryBuilder.setTables(TABLE_NAME);
// String[] asColumnsToReturn = new String[] { COLUMN_ID, COLUMN_NAME,
// COLUMN_DATA, COLUMN_STATUS };
// Cursor mCursor = queryBuilder.query(dbSqlite, asColumnsToReturn, null,
// null, null, null, "title ASC");
// Log.d(Tag, "getCursor() получили курсор с базы конец");
final SQLiteDatabase db = this.getWritableDatabase();
columns = new String[] { COLUMN_ID, COLUMN_DATA, COLUMN_NAME, COLUMN_STATUS };
// selection = "data_id = ?";
// selectionArgs = new String[] {id_for_listtsk_today};
Cursor c = db.query("mytable", columns, null, null, null, null, null);
return c;
}
}
ActivityMain.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="fill_parent" android:background="#81BEF7" android:scrollbars="vertical">
<TableLayout android:id="#+id/TableLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" >
<TableRow>
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
</TableRow>
</TableLayout>
</LinearLayout>
my_list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/bcheck"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:focusable="false">
</CheckBox>
<TextView
android:id="#+id/txtTitle"
android:layout_width="138dp"
android:layout_height="?android:attr/listPreferredItemHeight"
android:focusable="false"
android:gravity="left|center_vertical"
android:text="Test" >
</TextView>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right|center_vertical"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/ImageButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.50"
android:clickable="true" >
</ImageButton>
</LinearLayout>
</LinearLayout>
I removed
c.close();
db.close();
and now its working fine.

null pointer exception at db insert

package com.omkarsoft.ImagePortofolio;
import java.util.ArrayList;
import com.omkarsoft.ImagePortofolio.dataBaseHelper;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class sqlQueries {
dataBaseHelper database;
SQLiteDatabase db ;
UrlList urllist ;
public sqlQueries( dataBaseHelper dbh , SQLiteDatabase db )
{
database = dbh;
this.db = db;
}
public sqlQueries() {
System.out.println("no are sqlqueries constructor");
}
public void insertIntoCompanyTable( String companyname ) {
db = database.getWritableDatabase(); // this works fine here
ContentValues values = new ContentValues();
values.put(dataBaseHelper.COMPANY_NAME, companyname);
System.out.println(values);
db.insert(dataBaseHelper.COMPANY_LIST, null, values);
}
public int getCompanyID( String companyName)
{
int id = 0 ;
Cursor c = null;
try {
db = database.getReadableDatabase(); // this works fine here
String query = "SELECT company_id FROM company_list WHERE company_name = '"+ companyName +"'";
c = db.rawQuery(query,null);
} catch (Exception e) {
System.out.println("In getCompanyID : " +e);
}
if (c != null ) {
if (c.moveToFirst()) {
id = c.getInt(c.getColumnIndex("company_id"));
}
}
return id;
}
public int getCompanies( String comp) {
int id = 0;
Cursor c = null;
ArrayList<String> names = new ArrayList<String>();
try {
db = database.getReadableDatabase(); // this works fine here
String query = "SELECT * FROM company_list ";
c = db.rawQuery(query, null);
} catch (Exception e) {
System.out.println(e);
}
if (c != null) {
if (c.getCount() == 0)
id = 1;
else {
if (c.moveToFirst()) {
do {
String name = c.getString(c.getColumnIndex("company_name"));
names.add(name);
} while (c.moveToNext());
}
if( names.contains(comp))
id = 0;
else
id = 1 ;
}
}
return id;
}
public void insertIntoImageTable( int companyid , String productname , String productdesc , byte[] bmp )
{
try
{
db = database.getWritableDatabase(); // blows here i get a NPE
ContentValues values = new ContentValues();
values.put(dataBaseHelper.COMPANY_ID, companyid);
values.put(dataBaseHelper.PRODUCT_NAME, productname);
values.put(dataBaseHelper.PRODUCT_DESCRIPTION, productdesc);
values.put(dataBaseHelper.PRODUCT_IMAGE, bmp);
System.out.println(values);
db.insertOrThrow(dataBaseHelper.IMAGE_DATA, null, values);
System.out.println(values);
}
catch( Exception e)
{
e.printStackTrace();
}
}
}
You need to open the DB for writing first like e.g.
SQLiteDatabase db = tdHelper.getWritableDatabase();
and tdHelper being an instance of
private static class TweetDBOpenHelper extends SQLiteOpenHelper
Just try to logcat every parameter you put in db.insert with String.valueOf(); You'll then see which parameter is null.

Categories

Resources