I have a code which does following -
Connect to a web service via HttpClient to PHP file
Returns a result from an SQL query
Returns format is a jArray (a JSONArray)
for(int i=0; i < jArray.length() ; i++) {
json_data = jArray.getJSONObject(i);
int id=json_data.getInt("id");
String name=json_data.getString("name");
Log.d(name,"Output");
}
When I look at the LogCat, I see all the "names" of the query, Each record is printed. I just need to plug these results into a ListView. How can I accomplish this ?
PS - I do not have a separate class for an ArrayAdapter. Could this be the reason ?
If you just want to display a list of textViews you don't need to override anything, you can just add all of the items into an arrayList and use an arrayAdapter.
Put a list view in your xml that is named android:list and then create your arrayAdapter with the textView you want to use.
After that all you have to do is call setListAdapter(mArrayAdapter) and it should populate your list.
ArrayList<String> items = new ArrayList<String>();
for(int i=0; i < jArray.length() ; i++) {
json_data = jArray.getJSONObject(i);
int id=json_data.getInt("id");
String name=json_data.getString("name");
items.add(name);
Log.d(name,"Output");
}
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_expandable_list_item_1, items));
setListAdapter(mArrayAdapter)
hope this helps!
I do not like to remap data while i already have them in a JSON array
so this is my code ... it is simple enough for me ....hope it helps
package ...;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class DataListFragment extends ListFragment{
JSONArray data;
public DataListFragment(){
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i("mycode", "DataListFragment onActivityCreated");
data=((MainActivity)this.getActivity()).data;
Log.i("mycode", "data length "+data.toString());
setEmptyText("No Data Here");
final JSONArrayAdapter adapter = new JSONArrayAdapter(this.getActivity(),data);
setListAdapter(adapter);
// Start out with a progress indicator.
//setListShown(false);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Insert desired behavior here.
Log.i("mycode", "Item clicked: " + id);
}
private class JSONArrayAdapter extends BaseAdapter {
JSONArray data;
Context context;
public JSONArrayAdapter(Context context,JSONArray data) {
super();
this.context=context;
this.data=data;
}
#Override
public int getCount() {
return data.length();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
try {
return data.getJSONObject(arg0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public boolean hasStableIds(){
return true;
}
#Override
public boolean isEmpty(){
return data==null || data.length()==0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.single_item, parent, false);
TextView textView1 = (TextView) rowView.findViewById(R.id.firstLine);
TextView textView2 = (TextView) rowView.findViewById(R.id.secondLine);
//ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
try {
JSONObject jo = (JSONObject) data.get(position);
textView1.setText(jo.getString("category_title"));
textView2.setText(jo.getString("description"));
} catch (JSONException e) {
e.printStackTrace();
}
return rowView;
}
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip" >
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:contentDescription="icon"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/secondLine"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_toRightOf="#id/icon"
android:ellipsize="marquee"
android:singleLine="true"
android:textSize="12sp" />
<TextView
android:id="#+id/firstLine"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/secondLine"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:textSize="16sp" />
</RelativeLayout>
Inside your for loop where you are printing the names, you should be loading an array list containing the values you would like to insert to the list later.
Notice that the example uses the following:
ArrayList< HashMap < String, String > > mylist = new ArrayList < HashMap < String, String > > ();
And you have an integer and a string to add to the structure so you could simply turn that ID into a String and problem solved.
Afterwards you can use a list adapter without the need of creating a separate class:
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main, new String[] { "name", "id" }, new int[] { R.id.item_title, R.id.item_subtitle });
Where "name" and "id" will be the keys in your map for the name and id values returned by json and item_title, item_subtitle the views to "adapt" the text on.
Put the data into an Array and use ArrayAdapter to bind data to a list items.
See the article on:
http://www.josecgomez.com/2010/05/03/android-putting-custom-objects-in-listview/
Related
I'm new to android. I'm building an app for city bus fare. I will use two spinners as 'starting' point and 'destination'. I want to match these two input and get the result as 'fare cost' in a textview. Please give me some easy idea of how to implement this.
use spinner.getSelectedItem() it return selected object or spinner.getSelectedItemPosition() it will return selected item position based on selection of both spinner you will calculate you fare cost
Here is the working example:
activity_main.xml:
<?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:orientation="vertical"
android:padding="24dp">
<TextView
android:id="#+id/text_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="30dp"
android:text="RESULT"/>
<Spinner
android:id="#+id/spinner_source"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp">
</Spinner>
<Spinner
android:id="#+id/spinner_destination"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp">
</Spinner>
</LinearLayout>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
TextView textResult;
Spinner spinnerSource;
Spinner spinnerDestination;
String source;
String destination;
int cost = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Views
textResult = (TextView) findViewById(R.id.text_result);
spinnerSource = (Spinner) findViewById(R.id.spinner_source);
spinnerDestination = (Spinner) findViewById(R.id.spinner_destination);
// Spinner Drop down elements
List<String> locations = new ArrayList<String>();
locations.add("Location 1");
locations.add("Location 2");
locations.add("Location 3");
// Initialize
source = locations.get(0);
destination = locations.get(0);
// Creating adapter for spinner
ArrayAdapter<String> adapterSpinnerSource = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, locations);
ArrayAdapter<String> adapterSpinnerDestination = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, locations);
// attaching data adapter to spinners
spinnerSource.setAdapter(adapterSpinnerSource);
spinnerDestination.setAdapter(adapterSpinnerDestination);
// Spinner item select listener
spinnerSource.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Source location
source = parent.getItemAtPosition(position).toString();
calculateCost();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinnerDestination.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Destination location
destination = parent.getItemAtPosition(position).toString();
calculateCost();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void calculateCost() {
if ((source.equals("Location 1") && destination.equals("Location 2"))
|| (source.equals("Location 2") && destination.equals("Location 1"))) {
cost = 100;
} else if ((source.equals("Location 1") && destination.equals("Location 3"))
|| (source.equals("Location 3") && destination.equals("Location 1"))) {
cost = 200;
} else if ((source.equals("Location 2") && destination.equals("Location 3"))
|| (source.equals("Location 3") && destination.equals("Location 2"))) {
cost = 300;
}
// Output
textResult.setText(String.valueOf(cost));
}
}
OUTPUT:
Hope this will help~
I am trying to declare a horizontal listview in my activity like this
private LinearLayout lay;
HorizontalListView listview;
however the HorizontalListView is highlighted in red and I get the error "Cannot resolve symbol HorizontalListView "
Java File
package com.xera.deviceinsight.home;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class SensorCharts extends Activity{
private LinearLayout lay;
HorizontalListView listview;
private double highest;
private int[] grossheight;
private int[] netheight;
private Double[] grossSal= {15000.0,15000.0,15000.25,15000.1,
15000.0,15000.0,15000.0,15000.0,
15000.25,15000.1,15000.0,15000.0};
private Double[] netSal = {12000.0,13000.0,14000.25,10000.1,
10000.0,9000.0,12000.0,13000.0,
14000.25,10000.1,10000.0,9000.0};
private String[] datelabel = {"Jan 12","Feb 12","Mar 12",
"Apr 12","May 12","Jun 12",
"Jul 12","Aug 12","Sep 12",
"Oct 12","Nov 12","Dec 12"};
public void onCreate(Bundle savedInstance)
{
super.onCreate(savedInstance);
setContentView(R.layout.main);
lay = (LinearLayout)findViewById(R.id.linearlay);
listview = (HorizontalListView) findViewById(R.id.listview);
List<Double> b = Arrays.asList(grossSal);
highest = (Collections.max(b));
netheight = new int[netSal.length];
grossheight= new int[grossSal.length];
//updateSizeInfo();
}
public class bsAdapter extends BaseAdapter
{
Activity cntx;
String[] array;
public bsAdapter(Activity context,String[] arr)
{
// TODO Auto-generated constructor stub
this.cntx=context;
this.array = arr;
}
public int getCount()
{
// TODO Auto-generated method stub
return array.length;
}
public Object getItem(int position)
{
// TODO Auto-generated method stub
return array[position];
}
public long getItemId(int position)
{
// TODO Auto-generated method stub
return array.length;
}
public View getView(final int position, View convertView, ViewGroup parent)
{
View row=null;
LayoutInflater inflater=cntx.getLayoutInflater();
row=inflater.inflate(R.layout.list, null);
DecimalFormat df = new DecimalFormat("#.##");
final TextView title = (TextView)row.findViewById(R.id.title);
TextView tvcol1 = (TextView)row.findViewById(R.id.colortext01);
TextView tvcol2 = (TextView)row.findViewById(R.id.colortext02);
TextView gt = (TextView)row.findViewById(R.id.text01);
TextView nt = (TextView)row.findViewById(R.id.text02);
tvcol1.setHeight(grossheight[position]);
tvcol2.setHeight(netheight[position]);
title.setText(datelabel[position]);
gt.setText(df.format(grossSal[position]/1000)+" k");
nt.setText(df.format(netSal[position]/1000)+" k");
tvcol1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(SensorCharts.this, "Month/Year: "+title.getText().toString()+"\nGross Sal: "+grossSal[position], Toast.LENGTH_SHORT).show();
}
});
tvcol2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(SensorCharts.this, "Month/Year: "+title.getText().toString()+"\nNet Sal: "+netSal[position], Toast.LENGTH_SHORT).show();
}
});
return row;
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
updateSizeInfo();
}
private void updateSizeInfo() {
/** This is onWindowFocusChanged method is used to allow the chart to
* update the chart according to the orientation.
* Here h is the integer value which can be updated with the orientation
*/
int h;
if(getResources().getConfiguration().orientation == 1)
{
h = (int) (lay.getHeight()*0.5);
if(h == 0)
{
h = 200;
}
}
else
{
h = (int) (lay.getHeight()*0.3);
if(h == 0)
{
h = 130;
}
}
for(int i=0;i<netSal.length;i++)
{
netheight[i] = (int)((h*netSal[i])/highest);
grossheight[i] = (int)((h*grossSal[i])/highest);
System.out.println("net width[i] "+netheight[i]+"gross width[i] "+grossheight[i]);
}
listview.setAdapter(new bsAdapter(this,datelabel));
}
}
this is part of my xml I where I have the horizontal listview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
android:id="#+id/linearlay">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp"
android:gravity="center"
android:layout_gravity="center"
android:textColor="#000"
android:text="Bar Chart with out any jar"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:background="#ddd"
android:orientation="horizontal">
</RelativeLayout>
<com.xera.deviceinsight.home.HorizontalListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ddd"
/>
</LinearLayout>
Try to read this article which specifies how to use an HorizontalListView.
Declare your HorizontalListView in your XML and give it an id. Then you can use your element in your java functionality.
EDIT:
Here you have a tutorial about how implement easily a HorizontalListView. If you want a more customized version, read this.
There is a third option, which is here, where you can implement all the methods of HorizontalListView and use them (like mRect, setX, setY, onClickListener...).
MainActivity.java
its my main java class
package com.example.shikhu.newpractice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,DisplayList.class));
}
});
}
}
DisplayList.java
package com.example.shikhu.newpractice;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class DisplayList extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dsiplay_list);
BackgroundTask backgroundTask = new BackgroundTask(DisplayList.this);
backgroundTask.execute();
}
}
BackgroundTask.java
package com.example.shikhu.newpractice;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class BackgroundTask extends AsyncTask<Void,Fruit,Void> {
String json_string = "http://192.168.1.18:8081/fruitinfo/get_fruit_details.php";
Context ctx;
Activity activity;
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Fruit> arrayList = new ArrayList<>();
public BackgroundTask(Context ctx)
{
this.ctx=ctx;
activity = (Activity)ctx;
}
#Override
protected void onPreExecute() {
recyclerView = (RecyclerView)activity.findViewById(R.id.recyclerview);
layoutManager = new LinearLayoutManager(ctx);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
}
#Override
protected Void doInBackground(Void... params) {
try{
URL url = new URL(json_string);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while((line=bufferedReader.readLine())!=null)
{
stringBuilder.append(line + "\n");
}
httpURLConnection.disconnect();
String json_string = stringBuilder.toString().trim();
JSONObject jsonObject = new JSONObject(json_string);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while (count<jsonArray.length())
{
JSONObject JO = jsonArray.getJSONObject(count);
count++;
Fruit fruit = new Fruit(JO.getString("name"),JO.getInt("calories"),JO.getDouble("fat"));
publishProgress(fruit);
}
Log.d("JSON STRING",json_string);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Fruit... values) {
arrayList.add(values[0]);
adapter.notifyDataSetChanged();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
RecyclerAdapter.java
package com.example.shikhu.newpractice;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {
private static final int TYPE_HEAD = 0;
private static final int TYPE_LIST = 1;
ArrayList<Fruit> arrayList = new ArrayList<>();
public RecyclerAdapter(ArrayList<Fruit> arrayList)
{
this.arrayList =arrayList;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_HEAD)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header_layout,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
else if (viewType == TYPE_LIST)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
if (holder.viewType == TYPE_LIST) {
Fruit fruit = arrayList.get(position);
holder.Name.setText(fruit.getName());
holder.Calories.setText(Integer.toString(fruit.getCalories()));
holder.Fat.setText(Double.toString(fruit.getFat()));
}
}
#Override
public int getItemCount() {
return arrayList.size();
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder
{
TextView Name,Calories,Fat;
int viewType;
public RecyclerViewHolder(View v,int viewType)
{
super(v);
if (viewType == TYPE_LIST) {
Name = (TextView) v.findViewById(R.id.name);
Calories = (TextView) v.findViewById(R.id.calories);
Fat = (TextView) v.findViewById(R.id.fat);
this.viewType = TYPE_LIST;
}else if (viewType == TYPE_HEAD)
{
this.viewType = TYPE_HEAD;
}
}
public int getItemViewType(int position)
{
if (position==0)
return TYPE_HEAD;
return TYPE_LIST;
}
}
}
Fruit.java
package com.example.shikhu.newpractice;
public class Fruit {
private String name;
private int calories;
private Double fat;
public Fruit(String name,int calories,Double fat)
{
this.setName(name);
this.setCalories(calories);
this.setFat(fat);
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
}
public int getCalories()
{
return calories;
}
public void setCalories(int calories)
{
this.calories=calories;
}
public Double getFat()
{
return fat;
}
public void setFat(Double fat)
{
this.fat=fat;
}
}
Row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="75dp"
android:layout_marginRight="15dp"
android:layout_marginLeft="15dp"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:textStyle="bold"
android:textSize="20dp"
android:text="Name"
android:id="#+id/name"
android:layout_weight="0.39" />
<TextView
android:layout_width="79dp"
android:layout_height="match_parent"
android:text="Calorie"
android:gravity="center_vertical"
android:textSize="20dp"
android:textStyle="bold"
android:id="#+id/calories"
android:layout_marginLeft="40dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Fat"
android:gravity="center_vertical"
android:textSize="20dp"
android:textStyle="bold"
android:id="#+id/fat"
android:layout_weight="0.15"
android:layout_marginLeft="60dp" />
</LinearLayout>
Header_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="65dp"
android:background="?attr/colorPrimary">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:textStyle="bold"
android:textSize="20dp"
android:text="Name"
android:id="#+id/name1"
android:layout_weight="0.20"
android:textColor="#ffffff"
android:layout_marginLeft="10dp" />
<TextView
android:layout_width="79dp"
android:layout_height="match_parent"
android:text="Calorie"
android:gravity="center_vertical"
android:textSize="20dp"
android:textStyle="bold"
android:id="#+id/calories1"
android:layout_marginLeft="10dp"
android:textColor="#ffffff"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Fat"
android:gravity="center_vertical"
android:textSize="20dp"
android:textStyle="bold"
android:id="#+id/fat1"
android:layout_weight="0.15"
android:layout_marginLeft="60dp"
android:textColor="#ffffff"/>
</LinearLayout>
activity_display_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".DisplayList">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerview"></android.support.v7.widget.RecyclerView>
</RelativeLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.shikhu.newpractice.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display List"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
My Output
i dont know why it is showing text of textview rather the data fetched from database
enter image description here
PhpScript
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "fruit";
$con = mysqli_connect($host,$user,$pass,$db);
$query= "select * from fruit_details;";
$result = mysqli_query($con,$query);
$response = array();
while($row = mysqli_fetch_array($result))
{
array_push($response,array('name'=>$row[0],'calories'=>$row[1],'fat'=>$row[2 ]));
}
mysqli_close($con);
echo json_encode(array('server_response'=>$response));
?>
Your Adapter always return TYPE_HEAD i think this is wrong.
#Override
public int getItemViewType(int position) {
if (position == 0) {
return TYPE_HEAD;
} else {
return TYPE_LIST;
}
}
BackgroundTask.Java
package com.example.shikhu.newpractice;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class BackgroundTask extends AsyncTask<Void,Fruit,Void> {
String json_string = "http://127.0.0.1:8081/fruitinfo/get_fruit_details.php";
Context ctx;
Activity activity;
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Fruit> arrayList = new ArrayList<>();
public BackgroundTask(Context ctx)
{
this.ctx=ctx;
activity = (Activity)ctx;
}
#Override
protected void onPreExecute() {
recyclerView = (RecyclerView)activity.findViewById(R.id.recyclerview);
layoutManager = new LinearLayoutManager(ctx);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
}
#Override
protected Void doInBackground(Void... params) {
try{
URL url = new URL(json_string);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while((line=bufferedReader.readLine())!=null)
{
stringBuilder.append(line + "\n");
}
httpURLConnection.disconnect();
String json_string = stringBuilder.toString().trim();
JSONObject jsonObject = new JSONObject(json_string);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while (count<jsonArray.length())
{
JSONObject JO = jsonArray.getJSONObject(count);
count++;
Fruit fruit = new Fruit(JO.getString("name"),JO.getInt("calorie"),JO.getDouble("fat"));
publishProgress(fruit);
}
Log.d("JSON STRING",json_string);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Fruit... values) {
arrayList.add(values[0]);
adapter.notifyDataSetChanged();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
RecyclerAdapter.java
package com.example.shikhu.newpractice;
import android.support.annotation.IdRes;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {
private static final int TYPE_HEAD = 0;
private static final int TYPE_LIST = 1;
ArrayList<Fruit> arrayList = new ArrayList<>();
public RecyclerAdapter(ArrayList<Fruit> arrayList)
{
this.arrayList =arrayList;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_HEAD)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header_layout,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
else if (viewType == TYPE_LIST)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
if (holder.viewType == TYPE_LIST) {
Fruit fruit = arrayList.get(position-1);
holder.Name.setText(fruit.getName());
holder.Calories.setText(Integer.toString(fruit.getCalories()));
holder.Fat.setText(Double.toString(fruit.getFat()));
}
}
#Override
public int getItemCount() {
return arrayList.size()+1;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder
{
TextView Name,Calories,Fat;
int viewType;
public RecyclerViewHolder(View v,int viewType)
{
super(v);
if (viewType == TYPE_LIST) {
Name = (TextView) v.findViewById(R.id.name);
Calories = (TextView) v.findViewById(R.id.calories);
Fat = (TextView) v.findViewById(R.id.fat);
this.viewType = TYPE_LIST;
}else if (viewType == TYPE_HEAD)
{
this.viewType = TYPE_HEAD;
}
}
}
#Override
public int getItemViewType(int position) {
if (position==0)
return TYPE_HEAD;
else
return TYPE_LIST;
}
}
I think you are not managing views for header in your view holder and from bind view holder it is everytime getting only header view in return; SO just debug your code and let me know that are you getting TYPE_LIST data view or not. Also make references for header view in View holder and set text to it also.
I found your problem.
Your method getItemViewType is inside your ViewHolder class. It needs to be moved to be inside your adapter class. Right now, since your adapter has no getItemViewType method, it assumes all view types are 0 (HEADER), and so nothing is being bound.
Move this method to your adapter class and all will work :)
Edit
Another option which should work for you is to stop using viewTypes all together. Since you're using the same viewHolder anyway, when you bind the view, instead of checking the viewType, check the position:
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view, TYPE_LIST);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
if (position > 0) {
Fruit fruit = arrayList.get(position-1);
holder.Name.setText(fruit.getName());
holder.Calories.setText(Integer.toString(fruit.getCalories()));
holder.Fat.setText(Double.toString(fruit.getFat()));
} else {
holder.Name.setText("Name");
holder.Calories.setText("Calories");
holder.Fat.setText("Fat");
}
}
So now, all your view types will be of type list. This is fine, because the layout is basically identical, only the values of the TextViews changes. Instead of using viewType, simply use the position. If the position is 0, set the header fields, otherwise, use the Fruit data.
I know this is not the solution you wanted - I can't seem to find why the viewType implementation doesn't work, however, this solution should give you the result you wanted.
Hope this helps!
I tried all possible cases but data is not showing in the list from database.my starting activity have list view which is to be empty in starting and when user fill the data and save it from another activity,ans press back button the data should be shown in the first activity which have list view.,but every time data is not show
MainActivty.java
package com.example.smscampaign;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class Campaign_Details extends Activity {
private Demo selectedAdapter;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_demostration);
TextView text1=(TextView) findViewById(R.id.text1);
TextView text2=(TextView) findViewById(R.id.text1);
DataBaseHandler info= new DataBaseHandler(this);
info.open();
String data=info.getData();
info.close();
String[] values= new String[]{ data };
//txt.setText(data);
// Button next=(Button) findViewById(R.id.next);
// Map<String, String[]> storage = new HashMap<String, String[]>();
// String[] tableItems = storage.get("ContactTable");
// next.setOnClickListener(this);
// final ListView listview = (ListView) findViewById(R.id.listview);
ListView listview1 = (ListView) findViewById(R.id.listview1);
// TextView emptyText = (TextView)findViewById(android.R.id.empty);
//listview.setEmptyView(findViewById(R.id.empty));
// TextView emptyText = (TextView)findViewById(android.R.id.empty);
// listview .setEmptyView(emptyText);
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
selectedAdapter = new Demo(this,values);
ListView listview = (ListView) findViewById(R.id.listview);
listview.setAdapter(selectedAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
Intent n = new Intent(getApplicationContext(), SmsSend.class);
startActivity(n);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.nextPage:
Intent i = new Intent(this,SmsSend.class);
startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
}
demo.java
package com.example.smscampaign;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Demo extends ArrayAdapter{
private Campaign_Details list1;
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
private Context context;
private String[] values;
public Demo(Context context, String[] values) {
super(context, R.layout.list);
this.context = context;
this.values = values;
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater vi = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list, null);
// get text view
TextView label = (TextView)v.findViewById(R.id.data);
if (convertView == null) {
v = vi.inflate(R.layout.list, parent, false);
}
else
v = convertView;
TextView text1 = (TextView) v.findViewById(R.id.data);
text1.setText(values[position]);
return v;
}
}
activity_list_demonstration.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:stretchColumns="3" >
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textcolour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:background="#drawable/green_circle" />
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="10dp"
android:text="Active Campaign"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#4AE56B" />
<TextView
android:id="#+id/textnum1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginRight="130dp"
android:background="#drawable/green_badge"
android:gravity="center"
android:text=" 0 "
android:textColor="#color/white" />
</TableRow>
</TableLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="240dp"
android:orientation="vertical" >
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:stretchColumns="3" >
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textcolour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:background="#drawable/grey_circle" />
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:text="Closed Campaign"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textnum2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginRight="130dp"
android:background="#drawable/grey_badge"
android:gravity="center"
android:text=" 0 "
android:textColor="#color/white" />
</TableRow>
</TableLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="140dp"
android:orientation="vertical" >
<ListView
android:id="#+id/listview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text" >
</TextView>
</LinearLayout>
DatabaseHandler.java// databaseclass
package com.example.smscampaign;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHandler{
public static final String KEY_ROWID="_id";
public static final String KEY_NAME="person_name";
public static final String KEY_SCALE="scale_person";
private static final String DATABASE_NAME="Scaledb";
private static final String DATABASE_TABLE="peopleTable";
private static final int DATABASE_VERSION=1;
private DbHelper ourHepler;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL( "CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_SCALE + " TEXT NOT NULL );"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS" + DATABASE_TABLE);
onCreate(db);
}
}
public DataBaseHandler(Context c){
ourContext=c;
}
public DataBaseHandler open() throws SQLException{
ourHepler = new DbHelper(ourContext);
ourDatabase= ourHepler.getWritableDatabase();
return this;
}
public void close()
{
ourHepler.close();
}
public long entryCreate(String name, String scale) {
// TODO Auto-generated method stub
ContentValues cv=new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_SCALE, scale);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] col= new String[]{KEY_ROWID,KEY_NAME,KEY_SCALE};
Cursor c= ourDatabase.query(DATABASE_TABLE, col, null, null, null, null, null);
String run="";
int iRow=c.getColumnIndex(KEY_ROWID);
int iName=c.getColumnIndex(KEY_NAME);
int iScale=c.getColumnIndex(KEY_SCALE);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
run=run+c.getString(iRow)+ " " + c.getString(iName) + " " + c.getString(iScale) + "\n";
}
return run;
}
public String getScale(long l) {
// TODO Auto-generated method stub
String[] col= new String[]{KEY_ROWID,KEY_NAME,KEY_SCALE};
Cursor c= ourDatabase.query(DATABASE_TABLE, col,KEY_ROWID + "-" + l, null, null, null, null);
if(c != null){
c.moveToFirst();
String scale=c.getString(2);
return scale;
}
return null;
}
public String getName(long l) {
// TODO Auto-generated method stub
String[] col= new String[]{KEY_ROWID,KEY_NAME,KEY_SCALE};
Cursor c= ourDatabase.query(DATABASE_TABLE, col,KEY_ROWID + "-" + l, null, null, null, null);
if(c != null){
c.moveToFirst();
String name=c.getString(1);
return name;
}
return null;
}
public void updateEntry(long lt, String mName, String mScale) {
// TODO Auto-generated method stub
ContentValues cvUpdate=new ContentValues();
cvUpdate.put(KEY_NAME,mName);
cvUpdate.put(KEY_SCALE,mScale);
ourDatabase.update(DATABASE_TABLE, cvUpdate, KEY_ROWID + "-" + lt, null);
}
public void deleteEntry(long ltt) throws SQLException{
// TODO Auto-generated method stub
ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + ltt,null);
}
}
You need to change at some places. You have declared your arraylist globally as a
private ArrayList<String> list;
after that again you have declared on onCreate() method
final ArrayList<String> list = new ArrayList<String>();
So replace that by
list = new ArrayList<String>();
Now in your all data is added in your list but in your adapter you have passed values string array. So you also need to change from
selectedAdapter = new Demo(this,values);
to
selectedAdapter = new Demo(this,list);
Change the getview method contents.
public static class ViewHolder{
public TextView text;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.list, null);
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.data);
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
Also if you are not customizing layout[using only a textview] use the arrayadapter straightaway by choosing default layout.
in your ArrayAdapter you wrote
if (convertView == null) {
v = vi.inflate(R.layout.list, parent, false);
} else
v = convertView;
Remove the else statement. or rather remove the complete if-else statement. Also
TextView text1 = (TextView) v.findViewById(R.id.data); is extra you have already defined this specific TextView in label
EDIT
public Demo(Context context, String[] values) {
super(context, R.layout.list);
this.context = context;
this.values = values;
}
to
public Demo(Context context, String[] values) {
super(context, R.layout.list,values);
this.context = context;
this.values = values;
}
press back button the data should be shown in the first activity
You write your database loading code in onCreate() method which executes once in its life-cycle i.e when your application starts or when activity destroyed like in orientation changes.
So when you press back button the onCreate() has not called and the same will be continue with list.
Some suggessions:
its good if you write all database stuff in your onResume()
otherwise call finish() in your onPause() method of your main activity and again start it through intent in back pressed method of your second_activity..finish() kills the activity when you go to next one ..and again recreate when you come from the second through strtaActivity followed by its corresponding intent.
And also its better if you use StringTokenizer when you get data from database and put into String array.
for an app I am making I am attempting to populate a listView with data obtained from parse.com using a custom parsequeryadapter subclass. Basically it just shows a blank activity when opening the activity.
Adapter code
package com.example.battlesim;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import com.parse.ParseQueryAdapter;
import com.parse.ParseObject;
public class LeaderboardAdapter extends ParseQueryAdapter<ParseObject> {
public Context context;
public LeaderboardAdapter(Context c) {
super(c, new ParseQueryAdapter.QueryFactory<ParseObject>(){
public ParseQuery<ParseObject> create(){
// public final ArrayList<String> leadersName;
// public final ArrayList<Integer> leadersScore;
ParseQuery<ParseObject> queryL = ParseQuery.getQuery("Character");
queryL = queryL.whereNotEqualTo("name", null);
queryL = queryL.orderByDescending("level");
queryL.setLimit(10);
try {
queryL.find();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return queryL;
// queryL.findInBackground(new FindCallback<ParseObject>() {
// public void done(List<ParseObject> scoreList, ParseException e) {
// if (e == null) {
// for(int i = 0; i < 10; i++){
// leadersName.add(scoreList.get(i).getString("name"));
// leadersScore.add(scoreList.get(i).getInt("level"));
// }
// } else {
// Log.d("level", "Error: " + e.getMessage());
// }
// }
}
});
this.context = c;
}
public View getItemView(ParseObject o, View convertView, ViewGroup parent){
View vi = convertView;
if(convertView == null) vi = View.inflate(getContext(), R.layout.board, null);
super.getItemView(o, convertView, parent);
TextView name = (TextView) vi.findViewById(R.id.name);
TextView level = (TextView) vi.findViewById(R.id.level);
name.setText(o.getString("name"));
level.setText(o.getInt("level"));
return vi;
}
}
Activity onCreate code
LeaderboardAdapter adapter = new LeaderboardAdapter(this);
adapter.loadObjects();
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(adapter);
Board.xml
<?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="match_parent" >
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextView"
android:textSize="25dip"/>
<TextView
android:id="#+id/level"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="TextView"
android:textSize="25dip"/>
</RelativeLayout>
Sorry if I formatted anything oddly or forgot to include anything. I'm new to StackExchange and somewhat new to Android programming
Replace queryL.whereNotEqualTo("name", null); with queryL.whereExists("name");