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?
Related
This question already has answers here:
How to get value onListItemClick and pass it to another activity
(2 answers)
Closed 7 years ago.
i have a custom listview that fill from database and i want when click on any item value of textview pass to another activity, how should i do?
please help me!
this is all code , thanks u
source code:
Edit:
public class ListActivity extends Activity {
String value = "";
MovieDB myDbHelper;
SQLiteDatabase db;
ListAdapter adapter;
ArrayList<HashMap<String, String>> data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
final ListView lst=(ListView) findViewById(R.id.listView1);
Load_Database();
db = myDbHelper.getReadableDatabase();
Cursor c = db.rawQuery("select * from movie_list where product = '"+value+"' Or name like '%"+value+"%'" , null);
data = new ArrayList<HashMap<String, String>>();
for (; c.moveToNext();) {
HashMap<String, String> map = new HashMap<String, String>();
String img = c.getString(c.getColumnIndex("img"));
String name = c.getString(c.getColumnIndex("name"));
map.put("img", img);
map.put("name", name);
data.add(map);
}
adapter = new ListMovie(this, data);
lst.setAdapter(adapter);
lst.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
final Intent GoToDisplay = new Intent(ListActivity.this,DisplayActivity.class);
GoToDisplay.putExtra("position", data.get(arg2));
startActivity(GoToDisplay);
}
});
}
private void Load_Database() throws Error {
myDbHelper = new MovieDB(ListActivity.this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
}
}
Step 1:
Just get data from adapter using position in ListView.
For. e.g.
You have ArrayList<String> data;//
then access like,
GoToDisplay.putExtra("position", data.get(arg2)); // as arg2 referees to clicked item position from ListView
Step 2:
Get Clicked TextView from View
TextView clickedTextView = (TextView)arg1.findViewById(// Id of your TextView); // Or get child from view arg1
GoToDisplay.putExtra("position", clickedTextView.getText().toString());
Note: As we don't know your Adapter data, above code is just example for understanding..
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!
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.
This is a follow up question from my question thread exiting error in android
I created an async task but the values do not show up in the list view....
public class History extends Activity implements OnItemClickListener
{
/** Called when the activity is first created. */
ListView list;
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems;
//DEFINING STRING ADAPTER WHICH WILL HANDLE DATA OF LISTVIEW
ArrayAdapter<String> adapter;
private String resDriver,resPassenger,ID;
private ProgressDialog dialog;
ArrayList<HashMap<String, Object>> listInfo = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> item;
JSONObject jDriver;
//JSONObject jPassenger;
// Make strings for logging
private final String TAG = this.getClass().getSimpleName();
private final String RESTORE = ", can restore state";
private final String state = "Home Screen taking care of all the tabs";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent loginIntent = getIntent();
ID = loginIntent.getStringExtra("ID");
listItems = new ArrayList<String>();
Log.i(TAG, "Started view active rides");
setContentView(R.layout.searchresults);
list = (ListView)findViewById(R.id.ListView01);
list.setOnItemClickListener(this);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listItems);
list.setAdapter(adapter);
getInfo();
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3)
{
// TODO Auto-generated method stub
Toast.makeText(this, "u clicked " + listItems.get(position) ,Toast.LENGTH_LONG).show();
}
public void getInfo(){
DownloadInfo task = new DownloadInfo();
task.execute(new String[] { "http://www.vogella.de" });
}
private class DownloadInfo extends AsyncTask<String, Void , ArrayList<String>>{
#Override
protected ArrayList<String> doInBackground(String ... strings) {
ArrayList<String> listItems1;
jDriver = new JSONObject();
try {
jDriver.put("ID", ID);
jDriver.put("task", "GET DATES");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
listItems1 = new ArrayList<String>();
Log.i(TAG,"Sending data for the driver rides");
resDriver = HTTPPoster.sendJson(jDriver,"URL"); // Any Server URL
JSONObject driver;
try {
driver = new JSONObject(resDriver);
Log.i(TAG,"Recieved Driver details");
if ( driver.getString("DATABASE ERROR").equals("False")){
int length = Integer.parseInt( driver.getString("length"));
Log.i(TAG,"length is " + length);
for( int i =0 ; i< length ; i++){
String info = driver.getString(Integer.toString(i));
String[] array = info.split(",");
Log.i(TAG,"array is " + Arrays.toString(array));
Log.i(TAG,"Date "+ array.length);
Log.i(TAG,"DONE WITH THE LOOP");
//listInfo.add(item);
Log.i(TAG,"Date is"+array[0]);
listItems1.add(array[0]);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
listItems1.add("No driver rides created");
}
return listItems1;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
listItems = result;
adapter.notifyDataSetChanged();
}
}
}
The problem is that the values in the adapter do not get modified...
You initialize your adapter with a empty listItems, after your fill your listItems in AsyncTask. onPostExecute(), your adapter is not get updated, try this:
protected void onPostExecute(ArrayList<String> result) {
listItems = result;
adapter.addAll(ListItems);
adapter.notifyDataSetChanged();
}
Hope that help.
listItems = result; won't work, you need to use :
listItems.clear();
listItems.addAll(result);
If you create another list, your adapter won't know it, because it keeps a reference to the old list (which remains the same).
Please help with this error .... In the following code the get info function works correctly but it gives an error saying the thread caught an exception at exiting.... I am trying to use a tab host and the first tab page is the following... In this i show a progress dialog until i get my data and then show it in a list view
public class History extends Activity implements OnItemClickListener
{
/** Called when the activity is first created. */
ListView list;
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems;
//DEFINING STRING ADAPTER WHICH WILL HANDLE DATA OF LISTVIEW
ArrayAdapter<String> adapter;
private String resDriver,resPassenger,ID;
private ProgressDialog dialog;
ArrayList<HashMap<String, Object>> listInfo = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> item;
JSONObject jDriver;
//JSONObject jPassenger;
// Make strings for logging
private final String TAG = this.getClass().getSimpleName();
private final String RESTORE = ", can restore state";
private final String state = "Home Screen taking care of all the tabs";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent loginIntent = getIntent();
ID = loginIntent.getStringExtra("ID");
listItems = new ArrayList<String>();
Log.i(TAG, "Started view active rides");
setContentView(R.layout.searchresults);
list = (ListView)findViewById(R.id.ListView01);
list.setOnItemClickListener(this);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listItems);
list.setAdapter(adapter);
getInfo();
}
The function getInfo is used to start a thread which shows a dialog box and starts a http request to get some data ...
public void getInfo(){
GetInfoThread checkUpdate = new GetInfoThread();
checkUpdate.start();
dialog = ProgressDialog.show(History.this, "Retrieving Info","Please Wait ...", true);
}
private class GetInfoThread extends Thread
{
public void run() {
jDriver = new JSONObject();
try {
jDriver.put("ID", ID);
jDriver.put("task", "GET DATES");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
listItems = new ArrayList<String>();
Log.i(TAG,"Sending data for the driver rides");
resDriver = HTTPPoster.sendJson(jDriver,"http://dsadsada"); // Any Server URL
JSONObject driver;
try {
driver = new JSONObject(resDriver);
Log.i(TAG,"Recieved Driver details");
listItems.add(array[0]);
handler.sendEmptyMessage(0);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
listItems.add("No driver rides created");
handler.sendEmptyMessage(0);
}
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
dialog.dismiss();
Log.i(TAG,"hello 123");
adapter.notifyDataSetChanged();
}
};
}
I am not sure exactly what is causing your error but I suspect it has to do with UI changes not running on the actual UI thread. In Android there is a class called AsyncTask that will do the threading for you and handle the passing of data between the background thread an the UI thread. I would suggest rewriting your code to utilize the AsyncTask class.