How combine android SimpleCursorAdapter result? - java

I'm trying to populate sqlite records into a listview.
In my table, I'm splitting an address into columns e.g Street, Postcode, City & State.
I'm using SimpleCursorAdapter to load results into views like in the code below:
Here is my ListActivity.java
private DBManager dbManager;
private ListView listView;
private SimpleCursorAdapter adapter;
DbHelper myDb;
final String[] from = new String[] {
DbHelper.COL_NAME,
DbHelper.COL_STREET,
DbHelper.COL_POSTCODE,
DbHelper.COL_CITY,
DbHelper.COL_STATE };
final int[] to = new int[] { R.id.name, R.id.address };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_emp_list);
dbManager = new DBManager(this);
myDb = new DbHelper(this);
dbManager.open();
Cursor cursor = dbManager.fetch();
listView = (ListView) findViewById(R.id.list_view);
listView.setEmptyView(findViewById(R.id.empty));
adapter = new SimpleCursorAdapter(this, R.layout.activity_view_record, cursor, from, to, 0);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
Here is my view:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/name"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#id/id"
android:maxLines="1"
android:padding="3dp"
android:textSize="17sp"
android:textStyle="bold" />
<TextView
android:id="#+id/address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/nama"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#id/id"
android:ellipsize="end"
android:maxLines="2"
android:padding="3dp"
android:visibility="visible" />
</RelativeLayout>
My problem is, how to combine STREET, POSTCODE, CITY, STATE and put them into R.id.address?
Using the above method, i have to create a textview for each column, otherwise, it will error.

Make the following changes:
In your layout xml change
<TextView
android:id="#+id/address"
android:text="#string/format_address"
......
/>
In your strings.xm add the following:
<string name="format_address">%1$s, %2$s, %3$s, %4$s</string>
In your source code add the following:
Resources res = getResources();
String text = String.format(res.getString(R.string.format_address), STREET_VALUE, POSTCODE_VALUE, CITY_VALUE, STATE_VALUE);
NOTE STREET_VALUE, POSTCODE_VALUE, CITY_VALUE, STATE_VALUE replace with actual values or String ref.

Related

How to Display Data to Listview from SharedPreferences

I have two activity (DetailProduct and Wishlist) and i want to display data from DetailProduct to Wishlist, in here i using SharedPreferences for put data from DetailProduct to Wishlist.
This is my activity DetailProduct
wishlist.setOnClickListener(new View.OnClickListener() {
String imgpicaso = getIntent().getStringExtra("aaa");
String vardetailed = getIntent().getStringExtra("acb");
String thisname = getIntent().getStringExtra("name");
String text = getIntent().getStringExtra("abb");
#Override
public void onClick(View view) {
Intent tambah = new Intent(DetailProduct.this, Wishlist.class);
SharedPreferences sharedPreferences = DetailProduct.this.getSharedPreferences("baba", MODE_PRIVATE);
SharedPreferences.Editor shreditor = sharedPreferences.edit();
shreditor.putString("aaa", imgpicaso);
shreditor.putString("name", thisname);
shreditor.putString("abb", text);
shreditor.commit();
startActivity(tambah);
}
});
This is img DetailProduct
This is img Wishlist, please open this img
And this is file Wishlist.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wishlist);
setTitle("Your Wishlist");
ImageView resultgmb = (ImageView) findViewById(R.id.resultgmb);
TextView detailtok = (TextView) findViewById(R.id.detailtok);
TextView resulttext = (TextView) findViewById(R.id.resulttext);
Button bayarwish = (Button) findViewById(R.id.check);
Button hapus = (Button) findViewById(R.id.delete);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("baba", MODE_PRIVATE);
String imgpicaso = sharedPreferences.getString("aaa", "");
Picasso.with(getBaseContext()).load(imgpicaso).into(resultgmb);
String detailtext = sharedPreferences.getString("name", "");
detailtok.setText(detailtext);
String text = sharedPreferences.getString("ccc", "");
resulttext.setText("$: " +text);
listproduct = (ListView) findViewById(R.id.listproduct);
ArrayList<String> arrayList = new ArrayList<>();
ArrayAdapter<String> arr = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
listproduct.setAdapter(arr);
arr.notifyDataSetChanged();
}
this is xml Wishlist
<SearchView
android:id="#+id/search"
android:background="#color/cardview_light_background"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</SearchView>
<LinearLayout
android:orientation="vertical"
android:id="#+id/relone"
android:layout_below="#id/search"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:id="#+id/rel"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:src="#drawable/noimage"
android:id="#+id/resultgmb"
android:layout_width="130dp"
android:layout_height="130dp"
android:layout_alignParentRight="true"/>
<TextView
android:layout_marginTop="10dp"
android:text="setext"
android:textStyle="bold"
android:textColor="#000"
android:textSize="17dp"
android:id="#+id/detailtok"
android:layout_width="wrap_content"
android:layout_height="30dp" />
<TextView
android:text="setdescription"
android:layout_below="#id/detailtok"
android:textColor="#f00"
android:id="#+id/resulttext"
android:layout_width="wrap_content"
android:layout_height="30dp" />
<LinearLayout
android:layout_below="#id/resulttext"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="#+id/check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CHECK"/>
<Button
android:id="#+id/delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DELETE"/>
</LinearLayout>
<ListView
android:id="#+id/listproduct"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</RelativeLayout>
</LinearLayout>
Please help me, thank you
As #sark9012 pointed out, you might want to use Intent Data rather than shared preferences for that purpose. Here is a tutorial on that.
Edit
Although I'd really advise against using Shared Preferences data for the purpose you're looking for, it seems you got the code correct for retrieving the data from the Shared Preferences, what you might be missing out on is populating the ListView. This is the code you sent us:
listproduct = (ListView) findViewById(R.id.listproduct);
ArrayList<String> arrayList = new ArrayList<>();
ArrayAdapter<String> arr = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
listproduct.setAdapter(arr);
arr.notifyDataSetChanged();
I don't really see you populating the adapter with the data retrieved, so you might want to have a look into that. Check this example from CodePath on how to setup the ListView with an ArrayAdapter.
Generate comma separated string and store that in shared preference
while storing to SP.
like string1 = a1+","a2+","a3;
while retrieving from SP.
like array[] = string1.split(",");
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, array);

Searchable Dropdown spinner xamarin Android

Searchable Dropdown spinner
hi ,, I have spinner full by sqlite database I want can search in it
how can i do that
I try used Autocomplete text but not worked well
this my spinner.aXml
<Spinner
android:layout_width="match_parent"
android:layout_height="35dp"
android:id="#+id/SpinnerHotel"
android:paddingLeft="10dp"
android:background="#drawable/Spinner_Style"
android:spinnerMode="dropdown"
android:gravity="center"
android:visibility="visible"
android:layout_marginRight="10dp"
android:layout_marginTop="15dp"
android:layout_marginLeft="15dp" />
and text_View.axml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:id="#+id/autoCompleteTextView1"
android:textColor="#68767A"
android:text="Select a Hotel .. "
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:textSize="18dp" />
and this my Activity
async protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.GoShow_layout);
Agent = FindViewById<Spinner>(Resource.Id.SpinnerAgentt);
List<string> my_array = new List<string>();
my_array = await login.Get_Hotel();
ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Resource.Layout.Text_View, my_array);
adapter.SetDropDownViewResource(Resource.Layout.Text_View);
Hotel.Adapter = adapter;
Hotel.ItemSelected += Hotel_ItemSelected;
}
private void Agent_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
{
var Spinner = sender as Spinner;
string Agentt = Spinner.GetItemAtPosition(e.Position).ToString();
Toast.MakeText(this, Agentt , ToastLength.Short).Show();
}
I think you have to combine Spinner with AutoCompleteTextView, like here Combine Spinner and AutoCompleteTextView

Android App crashing with Error: Resource ID #0x7f0d0061 type #0x12 is not valid

I am trying to display DB records using a listView with SimpleCursorAdaptor. The app keeps crashing with the following error: Resource ID #0x7f0d0061 type #0x12 is not valid.
The crashing Java code is below
public class ViewActivity extends AppCompatActivity {
DatabaseHelper myDb;
ListView myList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
myDb = new DatabaseHelper(this);
myList = (ListView) findViewById(R.id.listViewLocations);
getListFromDb();
}
public void getListFromDb(){
Cursor res = myDb.ViewAll();
startManagingCursor(res);
//Map cursor from db to viewFields
String[] fromFieldNames = new String[]{DatabaseHelper.COL_2, DatabaseHelper.COL_3, DatabaseHelper.COL_4, DatabaseHelper.COL_5};
int[] toViewIDS = new int[]{R.id.viewName, R.id.viewAddress, R.id.viewPostcode, R.id.viewType};
//Create adaptor to map items from DB to UI
SimpleCursorAdapter myCursorAdaptor = new SimpleCursorAdapter(this, R.id.item_layout, res, fromFieldNames, toViewIDS, 0);
// Set adaptor for listView
myList.setAdapter(myCursorAdaptor);
}
The two XML files:
activity_view.xml
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listViewLocations"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
item_layout.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/viewName"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/viewAddress"
android:layout_below="#+id/viewName"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/viewPostcode"
android:layout_below="#+id/viewAddress"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/viewType"
android:layout_below="#+id/viewPostcode"
android:layout_alignParentStart="true" />
Why does it keep crashing and what can I do to fix it.
Cheers
The item_layout should be layout not id please change as below:
SimpleCursorAdapter myCursorAdaptor = new SimpleCursorAdapter(this, R.layout.item_layout, res, fromFieldNames, toViewIDS, 0);

Advice on android setlistadapter and combining two .xml layout

I am using two list adapter as shown on code below. resultList and resultList2 are initialized with new ArrayList <HashMap<String,String>>();
ListAdapter adapter, adapter2;
adapter =new SimpleAdapter(
getActivity(), resultList,
R.layout.list_item1, new String[]{TAG_ID, TAG_FRUIT, TAG_SPECIES},
new int[]{R.id.Id,R.id.fruit,R.id.species});
adapter2=new SimpleAdapter(
getActivity(), resultList2,
R.layout.list_item_append, new String[]{ TAG_NAME, TAG_ADDRESS, TAG_EMAIL},
new int[]{ R.id.name, R.id.address, R.id.email});
setListAdapter(adapter);
setListAdapter(adapter2); //this line has overriden setListAdapter(adapter)
I have two layouts named list_item1.xml and list_item2.xml.
//list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/Id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17sp"
android:textStyle="bold"
android:descendantFocusability="blocksDescendants"
android:visibility="gone"/><!--android:visibility="gone" -->
<TextView
android:id="#+id/fruit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17sp"
android:textStyle="bold" />
<TextView
android:id="#+id/species"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17sp"
android:textStyle="bold" />
</LinearLayout>
second layout: list_item2.xml
list_item.xml
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17sp"
android:textStyle="bold" />
<TextView
android:id="#+id/address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17sp"
android:textStyle="bold" />
<TextView
android:id="#+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17sp"
android:textStyle="bold" />
I have tried to use <include> and <merge> in my new layout but it is not the result I wanted. The result shows all the elements in adapter2. But there are empty list element before each of the adapter2 elements.
My expected result are:
adapter....
adapter....
adapter...
adapter2...
adapter2...
adapter2...
How can I achieve this? I think that setListAdapter is the cause of the problem.
The reason i used two listadapter is because i am trying two fetch two set of data from my database. The data is fetch from the table named tblfruit and tblperson.
$response["results"] = array();
$response["results2"] = array();
// temp user array
$results = array();
$results2=array();
while ($row = mysql_fetch_array($result)){
$results["id"] = $row["id"];
$results["fruit"] = $row["fruit"];
$results["species"] = $row["species"];
array_push($response["results"], $results);
}
while ($row = mysql_fetch_array($result2)){
$results2["name"] = $row["name"];
$results2["address"] = $row["address"];
$results2["email"] = $row["email"];
array_push($response["results2"], $results2);
}
Extend ListAdapter and inflate each row with your desired layout within the Adapter's View.getView() method. This method is called once for each row in the ListView (or record inside the adapter, if you want to be specific). It is used to set up (or, well, inflate) the view for each record, and doing things such as setting the value of TextView's, ImageView's, hiding unnecessary components for each row, etc. I haven't tried this with two differente layout resources myself, but I suppose it can be done with this approach.
public class CustomListAdapter extends ArrayAdapter<CustomObject> {
private Context context;
private int layoutResourceId_1;
private int layoutResourceId_2
private List<CustomObject> list;
public CustomListAdapter(Context context, int layoutResourceId_1, int layoutResourceId_2, List<CustomObject> list) {
super(context, layoutResourceId_1, list);
this.context = context;
this.layoutResourceId_1 = layoutResourceId_1;
this.layoutResourceId_2 = layoutResourceId_2;
this.list = list;
}
...
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutInflater layoutInflater = ((Activity) context).getLayoutInflater();
if(condition_layout_1()) {
row = layoutInflater.inflate(layoutResourceId_1, parent, false);
// Use a holder to prepare item
...
} else {
row = layoutInflater.inflate(layoutResourceId_2, parent, false);
// Use a holder to prepare item
...
}
return row;
}
...
}
You don't need to merge list_item1 and resultList2 layouts for whatever you are trying to achieve.Instead of extending ListActivity or ListFragment, use ordinary activity and setContentView with a layout that has two listviews in its xml like below
<?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="match_parent"
android:gravity="center"
android:orientation="vertical" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
</ListView>
<ListView
android:id="#+id/listView2"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
</ListView>
and then in your java file
ListView listview1 = (ListView) findViewById(R.id.listView1);
ListView listview2 = (ListView) findViewById(R.id.listView2);
listview1.setAdapter(adapter);
listview2.setAdapter(adapter2);
I am not sure if this meets your requirement.Sorry if it doesn't.I hope it helps.

Listview will not populate

Alright I'm stuck on populating a ListView in Android. This must be a tiring question for you guys but I can't find the problem. Basically it will produce placements in the ListView to hold texts, but it wont produce text. I checked my database class and it seems to be storing the data correctly, and I checked the syntax, but I cant find the problem.
Main activity that holds the list view
public class MainScreen extends ListActivity {
private TextView roommateId;
dbHelper db = new dbHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen);
Log.i("Created", "main created");
ArrayList<HashMap<String, String>> roommates = db.getAllRoommates();
if(roommates.size()!=0){
ListView listView = getListView();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
roommateId = (TextView) view.findViewById(R.id.roommateId);
String roommateIdValue = roommateId.getText().toString();
Intent intent = new Intent(getApplication(), RoommateView.class);
intent.putExtra("roommateId", roommateIdValue);
startActivity(intent);
}
});
ListAdapter adapter = new SimpleAdapter(MainScreen.this, roommates, R.layout.contact_entry,
new String[] {"roommateId", "firstName", "lastName"},
new int[]{R.id.roommateId, R.id.lastName, R.id.firstName});
setListAdapter(adapter);
}
}
Database code that returns the array list
public ArrayList<HashMap<String,String>> getAllRoommates(){
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
String query = "SELECT * FROM " + DB_TABLE;
SQLiteDatabase data = this.getWritableDatabase();
Cursor cursor = data.rawQuery(query, null);
if(cursor.moveToFirst()){
do{
HashMap<String,String> roommateMap = new HashMap<String, String>();
roommateMap.put(ID, cursor.getString(0));
Log.d("Roommate ID", cursor.getString(0));
roommateMap.put(FIRST_NAME, cursor.getString(1));
Log.d("First Name", cursor.getString(1));
roommateMap.put(LAST_NAME, cursor.getString(2));
list.add(roommateMap);
}while(cursor.moveToNext());
}
return list;
}
contact entry xml
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/last_name"
android:id="#+id/lastName"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/first_name"
android:id="#+id/firstName"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/id"
android:id="#+id/roommateId"/>
</TableRow>
Main screen xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000000" >
<TextView
android:id="#+id/contactsTitleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:layout_weight="1"/>
<Button
android:id="#+id/button1"
android:background="#444444"
android:onClick="showAddRoommate"
android:text="#string/add_roommate"
android:textColor="#FFFFFF"
android:textSize="20sp" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
</ListView>
</TableRow>
</TableLayout>
Alright, I think I found the problem, it was that the String array in the simple adapter wasn't corresponding to the hash map key values, so when it was looking for key values that were not in the Hash Map. Change that and it populated. Putting the answer down incase anyone in the future sees this post.

Categories