Hi i have provided my code below. I have one Main UI thread and one manual thread. I am updating the listView inside the thread and using it in an adapter and list view to populate. But the problem is once the activity starts the list is empty and only when the configuration changed it gets updated with the adapter. whats the problem in it? My thread is starting only after the oncreate is complete? Kindly leave the cursor part as I am getting all the values very well. Kindly help me friends.
public class MediaActivity extends Activity {
private static final String TAG = null;
ExpandableListView expList ;
ExpandableListAdapter expListAdapter;
static ArrayAdapter<String> ap;
static List<String> albumHead = new ArrayList<String>();
static HashMap<String, List<String>> albumChild = new HashMap<String, List<String>>();
static Cursor albumCursor;
AlbumThread albumThread;
#Override
protected void onStart() {
super.onStart();
albumThread = new AlbumThread();
albumThread.start();
Log.d(TAG , "albumThread Started");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media);
ListView expList = (ListView)findViewById(R.id.mediaList);
ap = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, albumHead);
if(!albumHead.isEmpty()){
expList.setAdapter(ap);
} else {
Toast makeToast = Toast.makeText(getApplicationContext(), "albumHead is empty" , Toast.LENGTH_LONG);
makeToast.show();
}
}
private static class AlbumThread extends Thread{
Context appContext = MediaApp.getAppContext();
List<String> songList = new ArrayList<String>();
public AlbumThread() {
super("myThread");
}
#Override
public void run() {
// Query Media Contents from MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
super.run();
ContentResolver albumResolver = appContext.getContentResolver();
Uri mediaContentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] mediaColumns = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
};
String mediaSort = " " + MediaStore.Audio.Media.ALBUM + " ASC" + "," + MediaStore.Audio.Media.DISPLAY_NAME + " ASC";
albumCursor = albumResolver.query(mediaContentUri, mediaColumns, null, null, mediaSort);
//Extract values from Cursor
if(albumCursor.moveToFirst()){
do{
int albumIdx = albumCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM);
int songIdx = albumCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
String albumString = albumCursor.getString(albumIdx);
String songString = albumCursor.getString(songIdx);
if(!albumHead.contains(albumString)){
albumHead.add(albumString);
ap.notifyDataSetChanged();
}
if(albumHead.contains(albumString)){
songList.add(songString);
albumChild.put(albumString, songList);
}
}while (albumCursor.moveToNext());
}
}
}
#Override
protected void onStop() {
super.onStop();
albumThread = null;
Log.d(TAG, "albumThread stopped yapee");
}
}
Related
I am trying to view the content of my database by listing it in a ListView. What am i doing wrong? The goal is to load a list of the database data when the page loads after a button click on the homepage.
The XML page simply has a ListView, named "studentList", inside a ScrollView
Java code:
public class edit_student extends AppCompatActivity {
private dbasemanager dBase;
private ListView studentInfoList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_student);
dBase.openReadable();
studentInfoList = (ListView)findViewById(R.id.studentList);
ArrayList<String> dBaseContent = dBase.retrieveRows();
ArrayAdapter<String> arrayAdpt = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, dBaseContent);
studentInfoList.setAdapter(arrayAdpt);
dBase.close();
}
}
This is openReadable() Function:
public dbasemanager openReadable() throws android.database.SQLException {
helper = new SQLHelper(context);
db = helper.getReadableDatabase();
return this;
}
This is the retrieveRows() Function:
public ArrayList<String> retrieveRows() {
ArrayList<String> studentRows = new ArrayList<>();
String[] columns = new String[] {"sid", "first_name", "last_name"};
Cursor cursor = db.query(Table_Name, columns, null, null, null, null, null);
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
studentRows.add(cursor.getString(0) + ", " + cursor.getString(1)
+ ", " + cursor.getString(2));
cursor.moveToNext();
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return studentRows;
}
Logcat:
There is a null pointer in line 17.
You need to construct databasemanager object before call it
public class edit_student extends AppCompatActivity {
private dbasemanager dBase;
private ListView studentInfoList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_student);
// construct databasemanager
dBase = new dbasemanager(...);
dBase.openReadable();
studentInfoList = (ListView)findViewById(R.id.studentList);
ArrayList<String> dBaseContent = dBase.retrieveRows();
ArrayAdapter<String> arrayAdpt = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, dBaseContent);
studentInfoList.setAdapter(arrayAdpt);
dBase.close();
}
}
BTW, I recommend you to use java code conventions to name classes.
For example: edit_student should be editStudent and dbasemanager should be DBManager or DbManager.
Hy guys!
I've got a problem. My app should display all routes in a listview. But there is something wrong with the arrayadapter. If i try my arrayadapter like this:
ArrayAdapter<DefineRoute> adapter = new ArrayAdapter<DefineRoute>(
this, android.R.layout.simple_list_item_1,verbindungen.getVerbindungen());
it works, but it only display the objectname of DefineRoute and i wanna display the output of the cursor.
Ithink i should try:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1,verbindungen.getVerbindungen());
But here comes the error: Cannot resolve constructor ArrayAdapter
Here is my Acticity:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated constructor stub
super.onCreate(savedInstanceState);
setContentView(R.layout.planausgabelayout);
//Aufruf der TextViews
TextView txtStart = (TextView)findViewById(R.id.txtAusgabeStart);
TextView txtZiel = (TextView)findViewById(R.id.txtAusgabeZiel);
TextView txtZeit = (TextView)findViewById(R.id.txtAusgabeZeit);
intent = getIntent();
txtStart.setText(intent.getStringExtra("StartHaltestelle"));
txtZiel.setText(intent.getStringExtra("ZielHaltestelle"));
txtZeit.setText(intent.getStringExtra("Zeit"));
getRoute();
}
public void getRoute() {
lvList = (ListView)findViewById(R.id.lvList);
Verbindungen verbindungen = new Verbindungen(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1,verbindungen.getVerbindungen());
lvList.setAdapter(adapter);
}
Here is my Activity Define Route:
public class DefineRoute {
private String abfahrtszeit;
private String ankunftszeit;
private String dauer;
private String umstieg;
public DefineRoute(String abfahrtszeit, String ankunftszeit, String dauer, String umstieg)
{
this.abfahrtszeit = getAbfahrtszeit();
this.ankunftszeit = getAnkunftszeit();
this.dauer = getDauer();
this.umstieg = getUmstieg();
}
public String getAbfahrtszeit() {
return abfahrtszeit;
}
public String getAnkunftszeit() {
return ankunftszeit;
}
public String getDauer() {
return dauer;
}
public String getUmstieg() {
return umstieg;
}
}
Here is my Activity Verbindungen:
public class Verbindungen {
SQLiteDatabase db;
LinkedList<DefineRoute> route;
DefineRoute[] routeArray;
Context context;
DatabaseHelper myDbHelper = null;
public Verbindungen(Context context) {
route = new LinkedList<DefineRoute>();
this.context = context;
myDbHelper = new DatabaseHelper(context);
}
public DefineRoute[] getVerbindungen() {
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
db = myDbHelper.getReadableDatabase();
// Alle Daten der Datenbank abrufen mithilfe eines Cursors
Cursor cursor = db.rawQuery("SELECT strftime('%H:%M', f.abfahrt) AS Abfahrt," +
"strftime('%H:%M', f.ankunft) AS Ankunft," +
"strftime('%H:%M', strftime('%s',f.ankunft)- strftime('%s',f.abfahrt), 'unixepoch') AS Dauer," +
"r.name AS Route," +
"count(u.fahrt_id) AS Umstiege " +
"FROM scotty_fahrt f " +
"JOIN scotty_haltestelle start ON f.start_id = start.id " +
"JOIN scotty_haltestelle ziel ON f.ziel_id = ziel.id " +
"JOIN scotty_route r ON f.route_id = r.id " +
"LEFT OUTER JOIN scotty_umstiegsstelle u ON f.id = u.fahrt_id " +
"WHERE start.name = 'Linz/Donau Hbf (Busterminal)' " +
"AND ziel.name = 'Neufelden Busterminal (Schulzentrum)' " +
"GROUP BY u.fahrt_id",null);
cursor.moveToFirst();
int i=0;
while (cursor.moveToNext()){
//in this string we get the record for each row from the column "name"
i++;
}
routeArray = new DefineRoute[i];
cursor.moveToFirst();
int k =0;
while (cursor.moveToNext())
{
routeArray[k] = new DefineRoute(cursor.getString(0),cursor.getString(1),cursor.getString(2),
cursor.getString(3));
k++;
}
//here we close the cursor because we do not longer need it
//}
cursor.close();
myDbHelper.close();
return routeArray;
}
please help me.
Now i am creating a ArrayAdapter class where i define my ouput in the listview with:
public class RouteAdapter extends ArrayAdapter<DefineRoute>{
Activity context;
DefineRoute[] defineroute;
public RouteAdapter(Activity context, DefineRoute[] defineroute){
super(context, R.layout.layoutausgabe, defineroute);
this.defineroute = defineroute;
this.context = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View row = inflater.inflate(R.layout.layoutausgabe,null);
TextView txZeit = (TextView)row.findViewById(R.id.txZeit);
TextView txDauer = (TextView)row.findViewById(R.id.txDauer);
TextView txUmstieg = (TextView)row.findViewById(R.id.txUmstieg);
DefineRoute defineRoute = defineroute[position];
txZeit.setText(defineRoute.getAbfahrtszeit() + " - " + defineRoute.getAnkunftszeit());
txDauer.setText(defineRoute.getDauer());
txUmstieg.setText(defineRoute.getUmstieg());
return row;
}
}
How should i continue?
and what should my adapter look like?
Your ArrayAdapter<String> is type of String so pass String list to it's constructor instead of verbindungen.getVerbindungen() list of objects.
ArrarAdapter < T > is any type of class you can use
in your case ArrayAdapter so you need override toString method of DefineRoute class
in your case
#Override
public String toString() {
return ankunftszeit+" "+ankunftszeit;
//or what ever you want to displat
}
or there is other Solution is Create your Own adapter extending by BaseAdapter Class.
i need your help, i did display data in a list view but the problem is that i
want the data to be according to a specific value, that means if the id = 1, only the rows
concerned will be displayed, if you have any suggestions i would be very thankful :
here the code of :
public class MainActivity extends ListActivity {
private static final int FLAG_REGISTER_CONTENT_OBSERVER = 2;
private Cursor cursor;
SimpleCursorAdapter adapter = null;
Cursor c;
DBAdapter db = new DBAdapter(this);
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db.open();
populateListViewFromDB();
} catch (Exception e) {
Log.e("ERROR", "Error occured: " + e.toString());
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
private void populateListViewFromDB() {
Cursor cursor = db.getAllRecords();
startManagingCursor(cursor);
String[] databaseColumnNames = new String[] { DBAdapter.col_region, };
int[] toViewIDs = new int[] { R.id.text };
SimpleCursorAdapter myCursordapter = new SimpleCursorAdapter(this,R.layout.activity_main, cursor, databaseColumnNames, toViewIDs,FLAG_REGISTER_CONTENT_OBSERVER);
ListView list = (ListView) findViewById(android.R.id.list);
And my DBAdapter is :
private static final String MENAGE = "table_MENAGE";
public static final String _id = "Num_du_Questionnaire";
public Cursor getAllRecords() {
return db.query(MENAGE, new String[] { _id, col_region,
}, null, null, null,
null, null);
}
list.setAdapter(myCursordapter);
} }
As you may check in query documentation, function accepts a selection and selectionArgs parameters, corresponding to SQL WHERE clause.
So, to make a query limited to a specific id, just use:
db.query(MENAGE, new String[] { _id, col_region}, "id = ?", new String[] {_id}, null, null, null);
i have a problem in showing data coming from database sqlite, i looked for a solution
here i did found plenty but i couldn't make it work, the error i get is : Error occured:
java.lang.IllegalArgumentException: column '_id' does not exist !!
my code is :
public class MainActivity extends ListActivity {
private static final int FLAG_REGISTER_CONTENT_OBSERVER = 2;
private Cursor cursor;
private ArrayList<String> arr;
SimpleCursorAdapter adapter = null;
Cursor c;
DBAdapter db = new DBAdapter(this);
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db.open();
Button suivant = (Button)findViewById(R.id.com_quest);
suivant.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent l = new Intent(MainActivity.this,ActivityUn.class);
startActivity(l);
}
});
populateListViewFromDB();
} catch (Exception e) {
Log.e("ERROR", "Error occured: " + e.toString());
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
private void populateListViewFromDB() {
Cursor cursor = db.getAllRecords();
startManagingCursor(cursor);
Log.i("MyApp", "Total users: " + cursor.getCount());
Toast.makeText(getApplicationContext(),
"Number of rows: " + cursor.getCount(), Toast.LENGTH_LONG)
.show();
String[] databaseColumnNames = new String[] { DBAdapter._id };
int[] toViewIDs = new int[] { R.id.text };
SimpleCursorAdapter myCursordapter = new SimpleCursorAdapter(this,R.layout.activity_main, cursor, databaseColumnNames, toViewIDs,FLAG_REGISTER_CONTENT_OBSERVER);
ListView list = (ListView) findViewById(android.R.id.list);
list.setAdapter(myCursordapter);
} }
and in dbadapter is :
private static final String MENAGE = "table_MENAGE";
public static final String _id = "Num_du_Questionnaire";
public Cursor getAllRecords() {
return db.query(MENAGE, new String[] { _id
}, null, null, null,
null, null);
}
All CursorAdapters require that the Cursor includes a column called _id. Your Cursor contains just one column called Num_du_Questionnaire.
I'm at a lose with this one. Trying to take edittext from a list view and put them into an arraylist to use on another activity.
public class editpage extends ListActivity {
public static String editString;
private dbadapter mydbhelper;
public static ArrayList<String> editTextList = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_list);
mydbhelper = new dbadapter(this);
mydbhelper.open();
fillData();
}
public void fillData() {
Cursor e = mydbhelper.getUserWord();
startManagingCursor(e);
String[] from = new String[] {dbadapter.KEY_USERWORD,};
int[] to = new int[] {R.id.textType,};
SimpleCursorAdapter editadapter =
new SimpleCursorAdapter(this, R.layout.edit_row, e, from, to);
ListView list = getListView();
View footer = getLayoutInflater().inflate(R.layout.footer_layout, list, false);
list.addFooterView(footer);
setListAdapter(editadapter);
}
public void onClick(View footer){
final MediaPlayer editClickSound = MediaPlayer.create(this, R.raw.button50);
final EditText editText = (EditText) findViewById(R.id.editText);
for (int i = 0; i < getCount(); i++){
editTextList.add(editText.getText().toString());
}
editClickSound.start();
startActivity(new Intent("wanted.pro.madlibs.OUTPUT"));
};
//can't get my getcount to work dynamically. I want it to be based off how many items are shown in next code showing my cursor but can't get to work atm unless I set statically to prevent errors and move to next activity
private int getCount() {
// TODO Auto-generated method stub
return 10;
}
Cursor to filter data pulled from database
public Cursor getUserWord()
{
return myDataBase.query(USER_WORD_TABLE, new String[] {
KEY_ID,
KEY_CATEGORY,
KEY_SOURCE, KEY_TITLE, KEY_USERWORD
},
KEY_CATEGORY+ "=" + categories.categoryClick + " AND " + KEY_SOURCE+ "="
+source.sourceClick + " AND " + KEY_TITLE+ "=" + title.titleClick,
null, null, null, KEY_ID);
Cursor to filter data from database to show in listview
public Cursor getUserWord()
{
return myDataBase.query(USER_WORD_TABLE, new String[] {
KEY_ID,
KEY_CATEGORY,
KEY_SOURCE, KEY_TITLE, KEY_USERWORD
},
KEY_CATEGORY+ "=" + categories.categoryClick + " AND " + KEY_SOURCE+ "="
+source.sourceClick + " AND " + KEY_TITLE+ "=" + title.titleClick,
null, null, null, KEY_ID);
}
My next activity will be showing the edittext merged with a string from my database. I take this string and replace edit01, edit02 etc with the users input from edittext fields on previous activity
public class output extends ListActivity {
private dbadapter mydbhelper;
#Override
public void onCreate(Bundle savedInstantState){
super.onCreate(savedInstantState);
setContentView(R.layout.outview);
mydbhelper = new dbadapter(this);
mydbhelper.open();
fillData();
}
private final Runnable mTask = new Runnable(){
public void run(){
TextView textView = (TextView)findViewById(R.id.outputText);
String story = textView.getText().toString();
CharSequence modifitedText1 = Replacer.replace(story,
"edit01", Html.fromHtml("<font color=\"red\">"+ editpage.editTextList.get(0) +"</font>"));
CharSequence modifitedText2 = Replacer.replace(modifitedText1,
"edit02", Html.fromHtml("<font color=\"red\">"+ editpage.editTextList.get(1) +"</font>"));
textView.setText(modifitedText2);
}
};
private final Handler mHandler = new Handler();
private void fillData() {
Cursor st = mydbhelper.getStory();
startManagingCursor(st);
String[] from = new String[] {dbadapter.KEY_TITLESTORY};
int[] to = new int[] {R.id.outputText};
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, R.layout.out_row, st, from, to);
setListAdapter(adapter);
}
#Override
protected void onResume() {
mydbhelper.open();
mHandler.postDelayed(mTask, 10);
super.onResume();
}
#Override
protected void onPause() {
mydbhelper.close();
super.onPause();
}
}
The furthest I can get this to work is with one item. I will be having anywhere from 4-10 edittexts on the first activity I show here. But no matter what I've tried it will only display the text entered into the first edittext field. In it's current state it will fill edit01 & edit02 in the string from database with what was put in first edittext in previous activity.
Well was finally able to get this to work without changing to much. I had to fight with it and try a bunch of things. Figured I would share the answer in case someone tries something like this. It came down to changing (R.id.editText) to have its own unique id.
private void editId(){
if(findViewById(R.id.editText) == null){
}else{
for(int editI= 0; editI<getCount(); editI++){
EditText editText = (EditText) findViewById(R.id.editText);
editText.setId(editI);
m_edit.add(editI, editText);
}}
}
and calling editId() in my onclick for my footer button
I had to change my runnable to work dynamically but that is another issue.