Items from ListView to SQLite, SQLite to ListView - android

I'm trying to get all the items on my listview (I've attached some image uri) and put them in the database, then get them again and load them on the listview.
What I did is: String hex = array_list.toString(); and put that hex string in the database (sqlite).
FirstFragment:
ListView lv;
ArrayList<Uri> array_list = new ArrayList<Uri>();
ArrayAdapter<Uri> array_adapter;
OnCreate..
array_adapter = new ArrayAdapter<Uri>(getActivity(), android.R.layout.simple_list_item_1, array_list);
lv = (ListView) v.findViewById(R.id.list);
lv.setAdapter(array_adapter);
OnClick..
String hex = array_list.toString();
HashMap<String, String> rcfData = new HashMap<String, String>();
rcfData.put("dateTime", hex);
DataHolder dataHolder = new DataHolder(getActivity());
dataHolder.insertData(rcfData);
Here are the items before I put them in sqlite: (Before clicking OnClick)
SecondFragment:
ListView lv2;
ArrayList<Uri> array_list2 = new ArrayList<Uri>();
ArrayAdapter<Uri> array_adapter2;
OnCreate...
array_adapter2 = new ArrayAdapter<Uri>(getActivity(), android.R.layout.simple_list_item_1, array_list2);
lv2 = (ListView) v.findViewById(R.id.list2);
lv2.setAdapter(array_adapter2);
OnClick...
Intent intent = getActivity().getIntent();
String rcfDataId = intent.getStringExtra("unique_id");
DataHolder dataHolder = new DataHolder(getActivity());
HashMap<String, String> rcfData = dataHolder.get_rcfData(rcfDataId);
if(rcfData.size() !=0) {
String s = rcfData.get("dateTime");
Uri hello = Uri.parse(s);
array_list2.add(hello);
array_adapter2.notifyDataSetChanged();
}
The problem is, when I try to load that string from sqlite to listview of the SecondFragment, it became like this: (After clicking OnClick of SecondFragment)
What I want it to be like (after clicking OnClick of SecondFragment), is like this:
How can I load it like that?

I don't know DataHolder, and I don't know whether it's really backed by an sqlite DB, but this feels like a misuse - you'd probably want to insert each of your items from your ListView as a separate row to your table.
However, if you just want a quick workaround to make it work, you could just split the string you're reading, e.g:
if(rcfData.size() !=0) {
String s = rcfData.get("dateTime");
// Remove brackets
s = s.substring(1, s.length() - 1);
// Split string and insert to ListView
for(String sPart : s.split(", ")) {
Uri hello = Uri.parse(sPart);
array_list2.add(hello);
}
array_adapter2.notifyDataSetChanged();
}

Related

Android how to trim sharedpreferences name

I'm getting all sharedpreferences created by my app and I insert them in a spinner but every sharedpreferences displayed like "example.xml" etc. I want to trim .xml extension let them just names like "example".
File prefsdir = new File(getApplicationInfo().dataDir,"shared_prefs");
if(prefsdir.exists() && prefsdir.isDirectory()){
String[] list = prefsdir.list();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, android.R.id.text1,list);
Spinner sp = (Spinner) findViewById(R.id.tum_ilaclar);
sp.setAdapter(adapter);
}
You can use something like this create a new method:
String[] getList(String[] list){
String values[] = new String[list.length];
for(int i=0; i<list.length; i++){
String value = list[i];
values[i]=value.contains(".xml")?value.replace(".xml",""):value;
}
return values;
}
Then in your code change :
String[] list = prefsdir.list();
to
String[] list = getList(prefsdir.list());
This will remove the .xml part.

Listview showing duplicate values on execution

When I try to load data from SQLite database to my ListView each item is duplicated.
I double checked my database values while getting to the Cursor: there is no redundant data in it. But when I try to show in ListView I get duplicate entries. I tried other questions from this section, but nothing can solve my problem. I know that hash set can reduce redundant data. But I have no idea about how to use it.
Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.distance);
list = (ListView) findViewById(R.id.list);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
String[] fromwhere = { "code","name" };
int[] viewswhere = { R.id.id,R.id.name};
ADAhere = new SimpleAdapter(Distance.this, datas,
R.layout.simple_list_row, fromwhere, viewswhere);
list.setAdapter(ADAhere);
list.setOnItemClickListener(this);
}
private void openAndQueryDatabase() {
try {
datas = new ArrayList<Map<String, String>>();
DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("select distinct cust_code,cust_name from customer", null);
Log.v("detailss", c.toString());
while (c.moveToNext()){
HashMap<String, String> datanums = new HashMap<String, String>();
String custcode = c.getString(c.getColumnIndex("cust_code"));
datanums.put("code", custcode);
datas.add(datanums);
String name = c.getString(c.getColumnIndex("cust_name"));
datanums.put("name", name);
datas.add(datanums);
}
}
catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
}
Let's take a look at how you transfer data from the Cursor 'c' to the ArrayList<Map<String, String>> 'datas':
while (c.moveToNext()){
HashMap<String, String> datanums = new HashMap<String, String>();
String custcode = c.getString(c.getColumnIndex("cust_code"));
datanums.put("code", custcode);
datas.add(datanums);
String name = c.getString(c.getColumnIndex("cust_name"));
datanums.put("name", name);
datas.add(datanums);
}
Each Cursor position belongs to one database table row. (If we think of query results as very short-lived tables this is even true for queries with JOIN etc.)
In your code, we see that for each row you add a Map to the ArrayList in two places.
First, you put ("code", custcode) to the Map 'datanums' and add it to the List.
Then you put ("name", name) to the same object, i.e. 'datanums'. This means you changed the object which is already contained in the list.
You add this object to the List a second time. Now the List has pairs of identical elements and the ListView shows duplicate entries.
You need only one List element per row, so drop one of the datas.add(datanums); statements.

Android button click next display of listview of data in JSON

hi can you help me how to display the next 10 data in json by click the next button. i have 50 data and i want to display first 10. Then when I click the next button, 11-20 will display in listview. Ill post my code below and i dont have any idea how to do it. Also when i click previous button it will go back to previous listview which is 1-10. Thanks!
doctordata = new ArrayList<Map<String, String>>();
try {
jsonObject = new JSONObject(d);
jsonArray = jsonObject.optJSONArray("Doctors");
int arraylength = jsonArray.length();
for (int i = 0; i < arraylength; i++) {
Map<String, String> doctormap = new HashMap<String, String>();
JSONObject jsonChildNode = jsonArray.getJSONObject(i);
doctor = jsonChildNode.optString("Name").toString();
specialty = jsonChildNode.optString("Specialty").toString();
doctormap.put("name", doctor);
doctormap.put("specialty", specialty);
doctordata.add(doctormap);
}
String[] from = {"name", "specialty"};
int[] views = {R.id.doctorlist_name, R.id.doctorlist_specialty,};
final SimpleAdapter myadapter = new SimpleAdapter(MainActivity.this, doctordata, R.layout.doctor_list, from, views);
list.setAdapter(myadapter);
} catch (JSONException e) {
e.printStackTrace();
}
Define a class called Doctors, with fields String name and String Specialty, and add the Doctors to a list that you can iterate or convert to Array.
class Doctors {
private final String specialty;
private final String name;
public Doctors (){
specialty= "Spe1";
name = "name";
}
}
public String convertToJson(){
Gson gson = new Gson();
return gson.toJson(this);
}
Ok, there are several ways to do what do you want to achieve. I will explain you how I would do it:
Firts, in the doctorData arraylist you have all the items (50 items) that you need to show.
Create a partialDoctorData arraylist and assing to it only the first 10 items from doctorData, ok? and add this new arraylist to the SimpleAdaper.
So you will need to do instead of your code:
final SimpleAdapter myadapter = new SimpleAdapter(MainActivity.this, **partialDoctorData**, R.layout.doctor_list, from, views);
list.setAdapter(myadapter);
So when the user click in the next button, you can clean the partialDoctorData content, add from the 11-20 items from the original doctorData arrayList and and and directly call to the
myadapter.notifyDataSetChanged();
(you don't have to repeat the step to create a new SimpleAdapter, only changing the values of the arraylist and calling to this method, the content of the list is going to be updated with the content of the partialDoctorData)
Try ;)
Try this one:
Android ListView with Load More Button
You can use pagination when 10 items will be loaded after that you will call agin api to get next 10 items

Converting values of SQL Database into a String Array

I need to create a drop down list (spinner) in eclipse for Android whereby the drop down options can be created by the user.
To do this I've created a SQLiteDatabase, which I want to convert into a string array to be put into an array adapter, which can then be fed into the spinner.
Database details are:
DATABASE_NAME = "carddb"
DATABASE_TABLE = "cardtable"
Then the column I wish to read the values from is:
KEY_CARDDETAILS = "_carddetails";
Here is my code so far, adapted from another question on this site (Link: how to get the database value to a String array in android(sqlite Database))
myDB = cardtable.this.openOrCreateDatabase("carddb", MODE_PRIVATE, null);
Cursor cardcursor = cardDB.rawQuery("SELECT * FROM cardtable");
String[] cardstringarray = new String[cardcursor.getCount()];
cardcursor.moveToFirst();
int counter = 0;
while(cardcursor.moveToNext()){
String carddetailss = cardcursor.getString(cardcursor.getColumnIndex("NAME"));
cardstringarray[counter] = carddetailss;
counter++;
}
I'm getting an error under "myDB" and "cardtable", both errors saying they cannot be resolved into a variable!
PLEASE HELP!
Use this code
String[] displayName={};
ArrayList<String> List=new ArrayList<String>();
myDB = cardtable.this.openOrCreateDatabase("carddb", MODE_PRIVATE, null); Cursor cardcursor = cardDB.rawQuery("SELECT * FROM cardtable");
String[] cardstringarray = new String[cardcursor.getCount()];
cardcursor.moveToFirst();
int counter = 0;
while(cardcursor.moveToNext()){
String carddetailss = cardcursor.getString(cardcursor.getColumnIndex("NAME"));
List.add(carddetailss);
counter++;
}
if(List != null){
listEmail=(ListView)findViewById(R.id.listEmail);
listEmail.setVisibility(view.VISIBLE);
displayName=(String[])List.toArray(new String[0]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, displayName);
// Assign adapter to ListView
listEmail.setAdapter(adapter);
}
This is work for you. Use spinner instead of listView.

On Android, How do I display html in ListView?

I am feeding a ListView from a database in this way (nothing special), except
COL_TXT_TRANSL2 contains html formatting:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
mCurrBookID = extras.getString("BookID");
mCurrChapterNum = extras.getString("ChapterNum");
mCurrChapterTitle = extras.getString("ChapterTitle");
mGitaDB= Central.mDB;
this.setTitle(mCurrChapterNum+"."+mCurrChapterTitle);
setContentView(R.layout.chapterdisplay);
//set chapter intro
TextView tvIntro=(TextView) findViewById(R.id.textIntro);
tvIntro.setText(Html.fromHtml(extras.getString("ChapterIntro")));
try {
String[] columns = new String[] { mGitaDB.COL_TXT_TEXT_NUM, mGitaDB.COL_TXT_TRANSL2 };
int[] to = new int[] { R.id.number_entry, R.id.title_entry };
mCursor=mGitaDB.GetGitaTexts(mCurrBookID, mCurrChapterNum);
mAdapter = new SimpleCursorAdapter(this,
R.layout.textslist_row, mCursor, columns, to);
setListAdapter(mAdapter);
}
catch (Exception e) {
String err="Error: " + e.getMessage();
Toast toast = Toast.makeText(Central.context, err, 15000);
toast.show();
}
}
Now the problem is that the text displayed in this ListView has HTML formatting.
How can I make listview display this HTML formatting? Currently it is displayed as a plain text with all tags.
Assuming the HTML is fairly simple you can run it through this method: http://developer.android.com/reference/android/text/Html.html#fromHtml(java.lang.String) The resulting Spannable can be sent to a TextView in the ListView. Beware the fromHtml method is very slow and may slow down scrolling, you might want to cache the Spannables.
Define a CharSequence ArrayList, include all the elements from your database to be displayed in this arraylist as HTML. Include a personal TextView layout for the individual entities of the listView, and display the Charsequence in the list. I had made use of the following code for my app:
List<CharSequence> styledItems = new ArrayList<CharSequence>();
droidDB.open();
articles = droidDB.getAllArticleTitles(feed.feedId);
droidDB.close();
for (Article article : articles) {
styledItems.add(Html.fromHtml(article.title));
}
ArrayAdapter<CharSequence> notes =
new ArrayAdapter<CharSequence>(this, R.layout.feeds_row,styledItems);
setListAdapter(notes);
For the feeds_row.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="wrap_content"
android:textColor="#FFFFFF"/>
Hope this helps.
My problem was similar to yours. I was reading data from file in json format, where I have objects with id and text fields. text field is html. I have resolved problem this way:
ArrayList<MyObject> myObjectsList = new ArrayList<MyObject>();
ArrayList<HashMap<String, CharSequence>> tableElements = new ArrayList<HashMap<String, CharSequence>>();
String keyword = in.getStringExtra(TAG_KEYWORD);
InputStream is = this.getResources().openRawResource(R.raw.data);
JSONParser jParser = new JSONParser();
myObjectsList = jParser.searchForObjects(is, keyword);
for (MyObject element : myObjectsList)
{
String id = Integer.toString(element.id);
CharSequence text = Html.fromHtml(element.text);
// creating new HashMap
HashMap<String, CharSequence> map = new HashMap<String, CharSequence>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TEXT, text);
// adding HashList to ArrayList
tableElements.add(map);
}
ListAdapter adapter = new SimpleAdapter(this,tableElements,
R.layout.search_item,
new String[] { TAG_ID, TAG_TEXT.toString()}, new int[] {
R.id.exercise_id, R.id.text });
setListAdapter(adapter);

Categories

Resources