I've read through all posts I can find about simplecursoradapter and listview but I still can't seem to find the answer to my problem.
I have an Activity which contains a number of radio buttons, a button and a listview. The Activity first makes an http request to a web server to retrieve some data. The data from the server is written to the sqlite db on the device. Once data has been written to the db, the Activity regains control and creates a Cursor from the db, a SimpleCursorAdapter and sets the adapter as the listview adapter. All data is written ok to the db, I have looped through the elements in the cursor and it contains all expected elements, still no elements is displayed in my listview.
Activity.java:
public class MyActivity extends Activity {
private RadioButton rb1, rb2;
private Button addBut;
private ListView lv;
private LinearLayout statusLayout;
private ScrollView scroll;
private String username;
private DBHelper db;
private Cursor cursor;
private static final String userfk = "1";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
rb1 = (RadioButton)findViewById(R.id.rb1);
rb1.setChecked(true);
rb2 = (RadioButton)findViewById(R.id.rb2);
addBut = (Button)findViewById(R.id.addButton);
statusLayout = (LinearLayout)findViewById(R.id.statusLayout);
scroll = (ScrollView)findViewById(R.id.configscroll);
lv = (ListView)findViewById(R.id.profilesll);
//get data from server, made in asynchtask
getData();
}
MessageHandler called from AsynchTask code:
private class MyHandler extends Handler {
public MyHandler() {
}
public void handleMessage(Message msg) {
final Bundle b = msg.getData();
if (b.getString("result").equalsIgnoreCase(MyResult.ERROR) || b.getString("result").equalsIgnoreCase(MyResult.FAIL)) {
//Handle error
} else {
handleList();
statusLayout.setVisibility(View.GONE);
scroll.setVisibility(View.VISIBLE);
}
}
}
private void handleList() {
if (db == null) {
db = new DBHelper(this);
}
if (cursor == null) {
try {
cursor = db.getListCursor(userfk);
} catch (Exception e) {
err = e.getMessage();
}
if (cursor == null) {
Toast.makeText(MyActivity.this, err != null ? err : getResources().getString(R.string.myerror), Toast.LENGTH_LONG).show();
} else {
try {
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, new String[] {DBHelper.COLUMN_ID}, new int[] {android.R.id.text1});
lv.setAdapter(adapter);
} catch (RuntimeException e) {
Log.e("test", e.getMessage());
} catch (Exception e) {
Log.e("test", e.getMessage());
}
}
}
}
DBHelper class
public Cursor getListCursor(String userfk) throws Exception {
StringBuilder builder = new StringBuilder("select name as _id from mytable where userfk=?");
List<String> values = new ArrayList<String>();
values.add(userfk);
try {
return this.getReadableDatabase().rawQuery(builder.toString(), values.toArray(new String[values.size()]));
} catch (Exception e) {
Log.d("test", e.getMessage());
throw e;
}
}
I hope someone can give me a hint about what I'm doing wrong! Thanks for your help!
Related
I am busy with trying to get an array which i get from MSSQL to display in a table view form in my application. I have tried to google it but i cant seem to find an example of this. I have tried it but i am running into one small error.
I get the following error Cannot resolve constructor:Simpletabledata adapter[package.mainactivity, package.itemarray]
Here is my mainactivy.java class:
public class MainActivity extends AppCompatActivity {
static String[] spaceProbeHeaders={"Name"};
private ArrayList<ClassListItems> itemArrayList; //List items Array
private MyAppAdapter myAppAdapter; //Array Adapter
final TableView<String[]> tableView = (TableView<String[]>) findViewById(R.id.tableView);
private boolean success = false; // boolean
Connection conn; // Connection Class Initialization
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tableView.setHeaderBackgroundColor(Color.parseColor("#777777"));
tableView.setHeaderAdapter(new SimpleTableHeaderAdapter(this,spaceProbeHeaders));
tableView.setColumnCount(4);
itemArrayList = new ArrayList<ClassListItems>(); // Arraylist Initialization
// Calling Async Task
SyncData orderData = new SyncData();
orderData.execute("");
}
// Async Task has three overrided methods,
private class SyncData extends AsyncTask<String, String, String>
{
String msg = "Internet/DB_Credentials/Windows_FireWall_TurnOn Error, See Android Monitor in the bottom For details!";
ProgressDialog progress;
#Override
protected void onPreExecute() //Starts the progress dailog
{
progress = ProgressDialog.show(MainActivity.this, "Synchronising",
"Tableview Loading! Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
try
{
ConnectionClass conStr=new ConnectionClass();
conn =conStr.connectionclass();
//Connection Object
if (conn == null)
{
success = false;
}
else {
// Change below query according to your own database.
String query = "SELECT customer_first_name FROM cc_customer";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next())
{
try {
itemArrayList.add(new ClassListItems(rs.getString("customer_first_name")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e)
{
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
success = false;
}
return msg;
}
#Override
protected void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my listview
{
progress.dismiss();
Toast.makeText(MainActivity.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false)
{
}
else {
try {
//myAppAdapter = new MyAppAdapter(itemArrayList, MainActivity.this);
tableView.setDataAdapter(new SimpleTableDataAdapter(MainActivity.this,itemArrayList ));
} catch (Exception ex)
{
}
}
}
}
and here is my classlist.java file:
public class ClassListItems
{
public String name; //Name
public ClassListItems(String name)
{
this.name = name;
}
public String getName() {
return name;
}
Update
N.B: OP is using SortableTableView Library.
You need to import the following to solve Cannot resolve constructor:SimpleTableDataAdapter-
import de.codecrafters.tableview.toolkit.SimpleTableDataAdapter;
Original
Do you have SimpleTableDataAdapter class in your project? It seems it can't find the class so it is not in the same package. If it is in different package, you need to import it.
And on a different note, your .java file names should match the class name
And on another different note, have you tested that itemArrayList is actually populating? For Android-MSSQL, here is a tutorial pointer -
https://parallelcodes.com/connect-android-to-ms-sql-database-2/
There are many tutorials if you google it.
I have a fragment, and I want to load up the listview in a particular way from my sql lite database:
private ProductDbAdapter mDbHelper;
private ProductListAdapter productAdapter;
private View mView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Open Database Connection
mDbHelper = new ProductDbAdapter(getActivity());
try {
mDbHelper.open();
} catch (SQLException e) {
e.printStackTrace();
}
// Setup list view
productAdapter = new ProductListAdapter(getActivity(), R.layout.product_row);
ListView lv = (ListView) mView.findViewById(R.id.lvProducts);
lv.setAdapter(productAdapter);
Cursor productCursor = mDbHelper.fetchAll();
getActivity().startManagingCursor(productCursor);
int numProducts = productCursor.getCount();
for(int i =0; i< numProducts; i++) {
Product prdt = new Product();
// The line below is where it throws an exception //
prdt.Name = productCursor.getString(productCursor.getColumnIndexOrThrow(ProductDbAdapter.KEY_NAME));
prdt.type = productCursor.getString(productCursor.getColumnIndexOrThrow(ProductDbAdapter.KEY_TYPE));
String strDate = productCursor.getString(productCursor.getColumnIndexOrThrow(ProductDbAdapter.KEY_EXPDATE));
// format into local date/time format
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
try {
prdt.dateExpires = sdf.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
// Add to custom adapter
productAdapter.add(prdt);
productCursor.moveToNext();
}
}
Whenever I do this, It stalls on the first reference to the SQLLite Data. It says "com.android.internal.os.ZygoteInit$MethodAndArgsCaller" is the error. I've never gotten this before and I have no clue why this line would cause it since the activity is already created and started. What can I do to fix this?
I have a DbHelper Class which extends SQLiteOpenHelper.
I do Some Download and update the Database inside an Asynctask.
Inside an activity i got no problem and code works fine,
but when i use the ASynctask class inside a fragment problems occurs.
usually wherever i use a context an Exception happened, Especially with dbHelper.ClearDB()
Error:
DB Read ERROR:java.lang.NullPointerException:
Attempt to invoke virtual method 'java.util.ArrayList x.database.DBHelper.getAllItems()' on a null object reference
Here's the code :
public class StaggeredFragment extends Fragment
{
private DBHelper dbHelper;
private SharedPreferences preferences;
private ArrayList<DisItem> savedData;
private final String LINK1 = "myLink";
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dbHelper = new DBHelper(getActivity().getApplicationContext());
preferences = getActivity().getSharedPreferences("pid", Context.MODE_PRIVATE);
new LoaderAsyncTask("ALL").execute();
}
class LoaderAsyncTask extends AsyncTask<Void, Void, Boolean> {
String brand;
LoaderAsyncTask(String brand) {
this.brand = brand;
}
#Override
protected Boolean doInBackground(Void... params) {
Log.d(TAG,"RUnning");
String fetched;
InputStream is = null;
//Store Current Data before Sync
try {
savedData = dbHelper.getAllItems();
}catch (Exception e)
{
Log.d(TAG,"DB Read ERROR:"+e.toString());
return false;
}
try {
dbHelper.ClearDB();
}catch (Exception e)
{
Log.d(TAG,"DB Clear ERROR:"+e.toString());
return false;
}
// Open connection to server for html
try {
is = urlStream(LINK1);
} catch (Exception e) {
Log.e(TAG, "HTTP Error " + e.toString());
return false;
}
// Fetch HTML Data
try {
fetched = readIt(is);
// Log.d("fetched", fetched);
} catch (Exception e) {
Log.e(TAG, "Buffer Error " + e.toString());
return false;
}
// Parsing JSON
try {
if (!fetched.isEmpty())
InitialsJson(fetched);
}catch (JSONException e) {
Log.e(TAG, "JSON Error " + e.toString());
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if(!aBoolean)
RestoreData();
}
}
private void InitialsJson(String fetched) throws JSONException
{
JSONObject jsonObject = new JSONObject(fetched);
if (jsonObject.getInt("success") == 1) {
JSONArray array = jsonObject.getJSONArray("data");
for (int i = 0; i<array.length() ; i++) {
JSONObject object = array.getJSONObject(i);
DisItem disItem = new DisItem();
disItem.setPid(object.getString("pid"));
disItem.setLiked(preferences.getBoolean(String.valueOf(disItem.getPid()), false));
Log.d(TAG, disItem.toString());
dbHelper.insert(disItem);
}
}
}
This is Databace getallItems function
public ArrayList<DisItem> getAllItems()
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + DIS_TABLE_NAME + "", null);
ArrayList<DisItem> arrayList = new ArrayList<>();
cursor.moveToFirst();
while (! cursor.isAfterLast())
{
DisItem disItem = new DisItem(cursor);
arrayList.add(disItem);
cursor.moveToNext();
}
return arrayList;
}
I tried your code with same scenario in a small JUnit Test and it shows me that you have not initialized your ArrayList<DisItem> correctely in getAllItems() method may be thats why you are getting nullPointerException that is
Replace
ArrayList<DisItem> arrayList = new ArrayList<>();
With
ArrayList<DisItem> arrayList = new ArrayList<DisItem>();'
I corrected this thing and run the test again with some dummy values and it showed me correct result like:
public class Test
{
private ArrayList<DisItem> savedData;
#org.junit.Test
public void test() throws Exception
{
savedData = getAllData();
for(int a = 0; a < savedData.size(); a++){
System.out.println("ArrayList Data A= " + savedData.get(a).getA() + " B = " + savedData.get(a).getB());
}
}
}
private ArrayList<DisItem> getAllData()
{
ArrayList<DisItem> arrayList = new ArrayList<DisItem>();
DisItem disItem = new DisItem();
disItem.setA("AAAAAA");
disItem.setB("BBBB");
arrayList.add(disItem);
return arrayList;
}
private class DisItem
{
String a, b;
public void setA(String a)
{
this.a = a;
}
public void setB(String b)
{
this.b = b;
}
public String getA()
{
return this.a;
}
public String getB()
{
return this.b;
}
}
Output:
ArrayList Data A= AAAAAA B = BBBB
you cant access more than one SharedPreferences or SQLiteOpenHelper in Parallel.
My task is to create app that could get latest tweets from x account.
Here is my code what I've made. However I get result (more than 0) only if i set (as search string) my account name. Otherwise I get nothing. Could someone explain me why? I will appreciate for any help.
private ListView lv;
private EditText et;
private ArrayAdapter<String> adapter;
String[] values;
private Token token = null;
private Credential c = null;
private UserAccountManager m = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
et = (EditText) findViewById(R.id.editText1);
et.setText("twapime");
doRest();// first run, initialization, first search
}
private void doRest() {
initAccount();
initSearching();
}
private void initSearching() {
ArrayList<String> listax = getSearchResults(et.getText().toString());
initListViewAdapter(listax);
}
private void initListViewAdapter(ArrayList<String> listax) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, listax);
lv.setAdapter(adapter);
}
private void initAccount() {
token = new Token("xxxx",
"xxxx");
c = new Credential("xxxx",
"xxxx", token);
m = UserAccountManager.getInstance(c);
}
private ArrayList<String> getSearchResults(String userTwitter) {
ArrayList<String> lista = new ArrayList<String>();
try {
if (m.verifyCredential()) {
SearchDevice sd = SearchDevice.getInstance();
Query q1 = QueryComposer.from(userTwitter);
Tweet[] ts = sd.searchTweets(q1);
System.out.println(ts.length);
for (int i = 0; i < ts.length; i++) {
lista.add(ts[i].getString(MetadataSet.TWEET_CONTENT));
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (LimitExceededException e) {
e.printStackTrace();
}
return lista;
}
public void btnSearcher(View w) {//OnClickListener
initSearching();
}
I think it happens when someone block public information data for untrusted user.
I never got this working in a straightforward manner. Sorry if I'm being a little vague. I'll try to elaborate on what I'm trying to do. I am trying to build a listview that grabs its data from a webservice. Once I initialize a listview, I want to keep polling the webserver periodically and update the contents of the listview. For this I am doing something like this:
public class SampleAutoUpdateList extends Activity {
//Autoupdate handler
private Handler handler = new Handler();
private Runnable updater = new Runnable() {
public void run() {
/*
* Update the list
*/
try {
Log.i("UPDATE", "Handler called");
searchAdapter = getFeed(URL);
searchAdapter.notifyDataSetChanged();
handler.postDelayed(this, Configuration.REFRESH_INTERVAL);
} catch(Exception e) {
Log.e("UPDATE ERROR", e.getMessage());
}
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linearmode);
this.context = this;
searchAdapter = getFeed(URL);
LinearLayout l2 = (LinearLayout) findViewById(R.id.secondaryLayout);
ListView list = new ListView(context);
l2.addView(list);
// display UI
UpdateDisplay(list);
updater.run();
}
private SearchAdapter getFeed(String URL) {
try
{
SearchHandler handler = new SearchHandler();
URL url = new URL(URL);
String data = convertStreamToString(url.openStream());
data = data.substring(data.indexOf('['), data.length()-1);
handler.parseJSON(data);
return handler.getFeed();
}
catch (Exception ee)
{
// if we have a problem, simply return null
Log.e("getFeed", ee.getMessage());
return null;
}
}
private void UpdateDisplay(View searchView) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
searchList = (ListView) searchView;
myProgressDialog = ProgressDialog.show(this,
"Please wait...", "Loading search....", true);
new Thread() {
public void run() {
try{
Thread.sleep(2000);
} catch (Exception e) { }
runOnUiThread(new Runnable() {
#Override
public void run() {
if (searchAdapter == null)
{
Log.e("ERROR", "No Feed Available");
return;
}
searchAdapter.setContext(context);
searchList.setAdapter(searchAdapter);
searchList.setSelection(0);
}
});
// Dismiss the Dialog
myProgressDialog.dismiss();
}
}.start();
}
}
And the SearchHandler class is simple:
public class SearchHandler extends DefaultHandler {
SearchAdapter _adapter;
SearchItem _item;
public SearchHandler()
{
}
public SearchAdapter getFeed()
{
return _adapter;
}
public void parseJSON(String data) {
// TODO Auto-generated method stub
_adapter = new SearchAdapter();
JSONArray parseArray;
try {
parseArray = new JSONArray(data);
for (int i=0; i < parseArray.length(); i++) {
SearchItem item = new SearchItem();
JSONObject jsonUser = parseArray.getJSONObject(i);
item.set_from(jsonUser.getString ("from"));
item.set_msg(jsonUser.getString("msg"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
No matter what I do, the handler gets called and the new items are fetched, but the list is never refreshed... Any ideas on what could be going wrong?
Well, it is a little bit difficult to follow your code, since you only have a fragment of it, and few of the really relevant bits. For example, based on your available code, your list should be forever empty, since you never associate the searchAdapter with a ListView...at least in the code you have shown.
That being said, the following lines seem particularly odd:
searchAdapter = getFeed(URL);
searchAdapter.notifyDataSetChanged();
I am going to assume that getFeed() (not shown) creates a new ListAdapter of some sort. If getFeed() is creating a new ListAdapter, there is no need to call notifyDataSetChanged() on it, as its data set hasn't changed -- it's brand new. Moreover, unless you are associating this new ListAdapter to your ListView, the new ListAdapter will have no effect.
If I'm barking up the wrong tree, consider adding lines to your sample showing the implementation of getFeed() and where you are using searchAdapter.