Arraylist TextView - java

I created a TextView with an ArrayList, but the output is not showing any text, what am I doing wrong? The xml has all the different views defined in it, with the imageview and multiple textviews, but I cant seem to get it to display any text.
TextItem.java:
public class TextItem {
private int imageId;
private String description;
private String description_real;
private String openingtimes;
private String openingtimes_real;
private String prices;
private String prices_real;
public TextItem(int imageId,
String description,
String description_real,
String openingtimes,
String openingtimes_real,
String prices,
String prices_real) {
this.imageId = imageId;
this.description = description;
this.description_real = description_real;
this.openingtimes = openingtimes;
this.openingtimes_real = openingtimes_real;
this.prices = prices;
this.prices_real= prices_real;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getdescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getdescription_real() {
return description_real;
}
public void setdescription_real(String description_real) {
this.description_real = description_real;
}
public String getopeningtimes(){
return openingtimes;
}
public void setopeningtimes(String openingtimes) {
this.openingtimes = openingtimes;
}
public String getopeningtimes_real(){
return openingtimes_real;
}
public void setopeningtimes_real(String openingtimes_real) {
this.openingtimes_real = openingtimes_real;
}
public String prices(){
return prices;
}
public void setprices(String prices) {
this.prices = prices;
}
public String getprices_real(){
return prices_real;
}
public void setprices_real(String prices_real) {
this.prices_real = prices_real;
}
#Override
public String toString() {
return description + "\n" + description_real + "/n" + "/n" +
openingtimes + "\n" + openingtimes_real + "/n" + "/n" +
prices + "\n" + prices_real + "/n" + "/n" ;
}}
Air.java:
public class Air extends Activity {
public static final String[] description = new String[] {"Lorem"};
public static final String[] description_real = new String[] {"Lorem"};
public static final String[] openingtimes = new String[] { "Lorem"};
public static final String[] openingtimes_real = new String[] {"Lorem"};
public static final String[] prices = new String[] { "Lorem"};
public static final String[] prices_real = new String[] {"Lorem"};
public static final Integer[] images = {
R.drawable.hotel };
ImageView ImageView;
TextView TextView;
List<TextItem> TextItems;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.textview_item);
TextItems = new ArrayList<TextItem>();
for (int i = 0; i < description.length ; i++) {
TextItem item = new TextItem(images[i],
description[i],
description_real[i],
openingtimes[i],
openingtimes_real[i],
prices[i],
prices_real[i]);
TextItems.add(item);
ImageView = (ImageView) findViewById(R.id.picture);
TextView = (TextView) findViewById(R.id.description);
TextView = (TextView) findViewById(R.id.description_real);
TextView = (TextView) findViewById(R.id.openingtimes);
TextView = (TextView) findViewById(R.id.openingtimes_real);
TextView = (TextView) findViewById(R.id.prices);
TextView = (TextView) findViewById(R.id.prices_real);
}
}
}
.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/picture"
android:layout_width="80dp"
android:layout_height="80dp"
android:contentDescription="#string/image"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/picture"
android:paddingBottom="10dp"
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/description_real"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/description"
android:paddingLeft="10dp"
android:textColor="#666666"
android:textSize="14sp" />
<TextView
android:id="#+id/openingtimes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/description_real"
android:paddingBottom="10dp"
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/openingtimes_real"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/openingtimes"
android:paddingLeft="10dp"
android:textColor="#666666"
android:textSize="14sp" />
<TextView
android:id="#+id/prices"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/openingtimes_real"
android:paddingBottom="10dp"
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/prices_real"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/prices"
android:paddingLeft="10dp"
android:textColor="#666666"
android:textSize="14sp" />
</RelativeLayout>

textView.setText("SomeText") is missing
you should do this
yourTextView.setText(textItem.getDescription)
also you are assigning many values to the same textview inside a loop, this is wrong, u gonna have one textItems displayed
code
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
public class StackActivity extends Activity {
public static final String[] description = new String[] { "Lorem" };
public static final String[] description_real = new String[] { "Lorem" };
public static final String[] openingtimes = new String[] { "Lorem" };
public static final String[] openingtimes_real = new String[] { "Lorem" };
public static final String[] prices = new String[] { "Lorem" };
public static final String[] prices_real = new String[] { "Lorem" };
public static final Integer[] images = { R.drawable.ic_launcher };
android.widget.ImageView ImageView;
android.widget.TextView TextView;
List<TextItem> TextItems;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextItems = new ArrayList<TextItem>();
for (int i = 0; i < description.length; i++) {
TextItem item = new TextItem(images[i], description[i],
description_real[i], openingtimes[i], openingtimes_real[i],
prices[i], prices_real[i]);
TextItems.add(item);
ImageView = (android.widget.ImageView) findViewById(R.id.picture);
ImageView.setImageResource(TextItems.get(i).getImageId());
TextView = (android.widget.TextView) findViewById(R.id.description);
TextView.setText(TextItems.get(i).getdescription());
TextView = (android.widget.TextView) findViewById(R.id.description_real);
TextView.setText(TextItems.get(i).getdescription());
TextView = (android.widget.TextView) findViewById(R.id.openingtimes);
TextView.setText(TextItems.get(i).getopeningtimes());
TextView = (android.widget.TextView) findViewById(R.id.openingtimes_real);
TextView.setText(TextItems.get(i).getopeningtimes_real());
TextView = (android.widget.TextView) findViewById(R.id.prices);
TextView.setText(TextItems.get(i).prices());
TextView = (android.widget.TextView) findViewById(R.id.prices_real);
TextView.setText(TextItems.get(i).getprices_real());
TextView.setText(TextItems.get(0).getdescription());
}
}
}

Related

How to show arraylist data in recyclerview?

I have an ArrayList with repeated data, I want to show the first 5 items in the first row of recyclerview then the second 5 items in the second row, and so on. How can I achieve this in Recyclerview?
Arraylist: [2013-04-01, OB Int. Updated upto 31/03/2013, 0, 0, 0,
2013-09-10, Cont. For Due-Month 082013, 780, 239, 541, 2014-03-28,
Cont. For Due-Month 032014, 780, 239, 541, 2014-02-03, Cont. For
Due-Month 012014, 780, 239, 541, 2013-07-26, Cont. For Due-Month
072013, 780, 239, 541]
DataAdapter.java
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.MyViewHolder> {
private AppCompatActivity activity;
List<String> data = new ArrayList();
private LayoutInflater inflater;
class MyViewHolder extends RecyclerView.ViewHolder {
private final View saparator;
private final TextView txtLabel;
public MyViewHolder(View itemView) {
super(itemView);
this.txtLabel = (TextView) itemView.findViewById(R.id.detail_parameter);
this.saparator = itemView.findViewById(R.id.detail_value);
}
}
public DataAdapter(AppCompatActivity activity, List<String> data) {
this.activity = activity;
this.inflater = LayoutInflater.from(activity);
this.data = data;
}
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyViewHolder(this.inflater.inflate(R.layout.pfpassbook_item, parent, false));
}
#SuppressLint("WrongConstant")
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.txtLabel.setText((CharSequence) this.data.get(position));
holder.txtLabel.setTextSize(15.0f);
holder.txtLabel.setTextColor(this.activity.getResources().getColor(R.color.colorAccent));
}
public int getItemCount() {
return this.data.size();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private RecyclerView rcList;
public String platenum = null;
RelativeLayout idForSaveView;
public static ArrayList<String> statement;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView((int) R.layout.pfpassbook);
statement = (ArrayList<String>) getIntent().getSerializableExtra("statement");
setView();
idForSaveView = (RelativeLayout) findViewById(R.id.relate);
}
private void setView() {
this.rcList = (RecyclerView) findViewById(R.id.detail_recyclerview);
this.rcList.setLayoutManager(new GridLayoutManager(this, 5));
this.rcList.setHasFixedSize(true);
this.rcList.setAdapter(new DataAdapter(DetailActivity.this, statement));
}
}
pfpassbook_item.xml
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="0dp"
app:cardElevation="0dp"
app:cardBackgroundColor="#android:color/transparent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/design_default_color_error"
android:orientation="horizontal">
<TextView
android:id="#+id/detail_parameter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:paddingTop="2dp"
android:paddingBottom="2dp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
First of all you shouldn't be in this kind of situation.
You can fix it BY converting this data to some ArrayList of Objects where object will hold 5 values .
This is just to get you started and give you idea.
import java.util.ArrayList;
public class HelloWorld {
public static class Model {
String value1;
String value2;
String value3;
String value4;
String value5;
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
public String getValue2() {
return value2;
}
public void setValue2(String value2) {
this.value2 = value2;
}
public String getValue3() {
return value3;
}
public void setValue3(String value3) {
this.value3 = value3;
}
public String getValue4() {
return value4;
}
public void setValue4(String value4) {
this.value4 = value4;
}
public String getValue5() {
return value5;
}
public void setValue5(String value5) {
this.value5 = value5;
}
#Override
public String toString() {
return "Model{" +
"value1='" + value1 + '\'' +
", value2='" + value2 + '\'' +
", value3='" + value3 + '\'' +
", value4='" + value4 + '\'' +
", value5='" + value5 + '\'' +
'}';
}
}
public static void main(String[] args) {
System.out.println("Hello World");
String a[] = {"2013-04-01", "OBInt.Updatedupto31/03/2013", "0", "0", "0", "2013-09-10", "Cont.ForDue-Month082013", "780", "239", "541", "2014-03-28", "Cont.ForDue-Month032014", "780", "239", "541", "2014-02-03", "Cont.ForDue-Month012014", "780", "239", "541", "2013-07-26", "Cont.ForDue-Month072013", "780", "239", "541"};
ArrayList<Model> arrayList = new ArrayList<>();
for (int i = 0; i < a.length ; i = i + 5) {
Model m = new Model();
m.setValue1(a[i]);
m.setValue2(a[i + 1]);
m.setValue3(a[i + 2]);
m.setValue4(a[i + 3]);
m.setValue5(a[i + 4]);
arrayList.add(m);
}
System.out.println(arrayList.size() + "");
for(int i =0 ;i<arrayList.size();i++){
System.out.println(arrayList.get(i));
}
}
}
Provided that the size of the array will be in multiple of 5.
For me cleaning the data before setting to recyclerView is a good way to go as you can catch the errors before setting it on recyclerView.
Also by doing this you can use it in CustomAdapter to make desired View for your Items.
UPDATE 1:
DataAdapter
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.MyViewHolder> {
private AppCompatActivity activity;
ArrayList<Model> data = new ArrayList();
private LayoutInflater inflater;
class MyViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
private TextView textView2;
private TextView textView3;
private TextView textView4;
private TextView textView5;
public MyViewHolder(View itemView) {
super(itemView);
textView = (TextView)itemView.findViewById( R.id.textView );
textView2 = (TextView)itemView.findViewById( R.id.textView2 );
textView3 = (TextView)itemView.findViewById( R.id.textView3 );
textView4 = (TextView)itemView.findViewById( R.id.textView4 );
textView5 = (TextView)itemView.findViewById( R.id.textView5 );
}
}
public DataAdapter(AppCompatActivity activity, ArrayList<Model> data) {
this.activity = activity;
this.inflater = LayoutInflater.from(activity);
this.data = data;
}
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyViewHolder(this.inflater.inflate(R.layout.pfpassbook_item, parent, false));
}
public void onBindViewHolder(MyViewHolder holder, int position) {
Model m = data.get(position);
holder.textView.setText(m.getValue1());
holder.textView2.setText(m.getValue2());
holder.textView3.setText(m.getValue3());
holder.textView4.setText(m.getValue4());
holder.textView5.setText(m.getValue5());
}
public int getItemCount() {
return this.data.size();
}
}
setViewMethod:
private void setView() {
this.rcList = (RecyclerView) findViewById(R.id.detail_recyclerview);
this.rcList.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL,false));
this.rcList.setHasFixedSize(true);
String[] a = {"2013-04-01", "OBInt.Updatedupto31/03/2013", "0", "0", "0", "2013-09-10", "Cont.ForDue-Month082013", "780", "239", "541", "2014-03-28", "Cont.ForDue-Month032014", "780", "239", "541", "2014-02-03", "Cont.ForDue-Month012014", "780", "239", "541", "2013-07-26", "Cont.ForDue-Month072013", "780", "239", "541"};
ArrayList<Model> arrayList = new ArrayList<>();
for (int i = 0; i < a.length ; i = i + 5) {
Model m = new Model();
m.setValue1(a[i]);
m.setValue2(a[i + 1]);
m.setValue3(a[i + 2]);
m.setValue4(a[i + 3]);
m.setValue5(a[i + 4]);
arrayList.add(m);
}
this.rcList.setAdapter(new DataAdapter(this, arrayList));
}
Model Class :
public class Model {
String value1;
String value2;
String value3;
String value4;
String value5;
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
public String getValue2() {
return value2;
}
public void setValue2(String value2) {
this.value2 = value2;
}
public String getValue3() {
return value3;
}
public void setValue3(String value3) {
this.value3 = value3;
}
public String getValue4() {
return value4;
}
public void setValue4(String value4) {
this.value4 = value4;
}
public String getValue5() {
return value5;
}
public void setValue5(String value5) {
this.value5 = value5;
}
#Override
public String toString() {
return "Model{" +
"value1='" + value1 + '\'' +
", value2='" + value2 + '\'' +
", value3='" + value3 + '\'' +
", value4='" + value4 + '\'' +
", value5='" + value5 + '\'' +
'}';
}
}
pfpassbook_item.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="wrap_content">
<TextView
android:id="#+id/textView"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/textView3"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/textView4"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:id="#+id/textView5"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
You can design pfpassbook_item any way you want. always bind your data in Array of objects instead of adding one by one in the array.
You can use spanCount for showing desired quantity of items in a row like this
layoutManager!!.spanCount = 5
And in XML inside your recyclerview like this
app:spanCount="5"
You can use StaggeredGridLayoutManager as the layout of recyclerview
XML
<androidx.recyclerview.widget.RecyclerView
android:id="+#id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="androidx.recyclerview.widget.StaggeredGridLayoutManager"
app:spanCount="5" />
Here spanCount defines the number of items you want to display in a row
If you want to define using class
val layoutManager = StaggeredGridLayoutManager(5, StaggeredGridLayoutManager.VERTICAL)
recyclerView.layoutManager = layoutManager

create button on xml file (not new activity) and open new activity

I'm new in android studio and currently creating an app which will retrieve data from existing db of sqlite. based on what I'd found is to create a layout file (not by creating new empty activity) to design on how the display the data. But in the layout, I want the button to open new activity, but somehow it didn't and I didn't found any solution so far. and the image also didn't appeared. This is the code:
DataPOI.java
public class DataPOI {
private int id;
private String category;
private String name;
private String hour;
private String phone_number;
private String address;
private String website;
private int fee_adult_standard;
private int fee_child_standard;
private int fee_senior_standard;
private int fee_adult_MyKad;
private int fee_child_MyKid;
private int fee_senior_MyKad;
private int fee_student_standard;
private int fee_student_MyKad;
private String description;
private byte[] photo;
private String coordinate;
private String door;
private String parking1;
private String parking2;
public DataPOI(int id, String category, String name, String hour, String phone_number,
String address, String website, int fee_adult_standard, int fee_child_standard,
int fee_senior_standard, int fee_adult_MyKad, int fee_child_MyKid,
int fee_senior_MyKad, int fee_student_standard, int fee_student_MyKad,
String description, byte[] photo, String coordinate, String door,
String parking1, String parking2) {
this.id = id;
this.category = category;
this.name = name;
this.hour = hour;
this.phone_number = phone_number;
this.address = address;
this.website = website;
this.fee_adult_standard = fee_adult_standard;
this.fee_child_standard = fee_child_standard;
this.fee_senior_standard = fee_senior_standard;
this.fee_adult_MyKad = fee_adult_MyKad;
this.fee_child_MyKid = fee_child_MyKid;
this.fee_senior_MyKad = fee_senior_MyKad;
this.fee_student_standard = fee_student_standard;
this.fee_student_MyKad = fee_student_MyKad;
this.description = description;
this.photo = photo;
this.coordinate = coordinate;
this.door = door;
this.parking1 = parking1;
this.parking2 = parking2;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHour() {
return hour;
}
public void setHour(String hour) {
this.hour = hour;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public int getFee_adult_standard() {
return fee_adult_standard;
}
public void setFee_adult_standard(int fee_adult_standard) {
this.fee_adult_standard = fee_adult_standard;
}
public int getFee_child_standard() {
return fee_child_standard;
}
public void setFee_child_standard(int fee_child_standard) {
this.fee_child_standard = fee_child_standard;
}
public int getFee_senior_standard() {
return fee_senior_standard;
}
public void setFee_senior_standard(int fee_senior_standard) {
this.fee_senior_standard = fee_senior_standard;
}
public int getFee_adult_MyKad() {
return fee_adult_MyKad;
}
public void setFee_adult_MyKad(int fee_adult_MyKad) {
this.fee_adult_MyKad = fee_adult_MyKad;
}
public int getFee_child_MyKid() {
return fee_child_MyKid;
}
public void setFee_child_MyKid(int fee_child_MyKid) {
this.fee_child_MyKid = fee_child_MyKid;
}
public int getFee_senior_MyKad() {
return fee_senior_MyKad;
}
public void setFee_senior_MyKad(int fee_senior_MyKad) {
this.fee_senior_MyKad = fee_senior_MyKad;
}
public int getFee_student_standard() {
return fee_student_standard;
}
public void setFee_student_standard(int fee_student_standard) {
this.fee_student_standard = fee_student_standard;
}
public int getFee_student_MyKad() {
return fee_student_MyKad;
}
public void setFee_student_MyKad(int fee_student_MyKad) {
this.fee_student_MyKad = fee_student_MyKad;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public byte[] getPhoto() {
return photo;
}
public void setPhoto(byte[] photo) {
this.photo = photo;
}
public String getCoordinate() {
return coordinate;
}
public void setCoordinate(String coordinate) {
this.coordinate = coordinate;
}
public String getDoor() {
return door;
}
public void setDoor(String door) {
this.door = door;
}
public String getParking1() {
return parking1;
}
public void setParking1(String parking1) {
this.parking1 = parking1;
}
public String getParking2() {
return parking2;
}
public void setParking2(String parking2) {
this.parking2 = parking2;
}
}
ListPOIadapter.java
public class ListPOIadapter extends BaseAdapter {
private Context mContext;
private List<DataPOI> mPOIList;
public ListPOIadapter(Context mContext, List<DataPOI> mPOIList) {
this.mContext = mContext;
this.mPOIList = mPOIList;
}
#Override
public int getCount() {
return mPOIList.size();
}
#Override
public Object getItem(int i) {
return mPOIList.get(i);
}
#Override
public long getItemId(int i) {
return mPOIList.get(i).getId();
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = View.inflate(mContext, R.layout.data_layout, null);
//edit below this
ImageView myPhoto = (ImageView)v.findViewById(R.id.imageView);
TextView myName = (TextView)v.findViewById(R.id.name);
TextView myHour = (TextView)v.findViewById(R.id.operational_hour);
TextView myContact = (TextView)v.findViewById(R.id.contact_number);
TextView myWebsite = (TextView)v.findViewById(R.id.website);
TextView myAddress = (TextView)v.findViewById(R.id.address);
//myPhoto.setI(mPOIList.get(i).getPhoto());
myName.setText(mPOIList.get(i).getName());
myHour.setText(mPOIList.get(i).getHour());
myContact.setText(mPOIList.get(i).getPhone_number());
myWebsite.setText(mPOIList.get(i).getWebsite());
myAddress.setText(mPOIList.get(i).getAddress());
return v;
}
}
AmusementPark.java
public class AmusementPark extends AppCompatActivity {
private ListView lvPOI;
private ListPOIadapter adapter;
private List<DataPOI> mPOIList;
private AmusementPark_Helper mDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_amusement_park);
lvPOI = (ListView)findViewById(R.id.listview_product);
mDBHelper = new AmusementPark_Helper(this);
//Check existis database
File database = getApplicationContext().getDatabasePath(AmusementPark_Helper.DBNAME);
if(false == database.exists()) {
mDBHelper.getReadableDatabase();
//Copy db
if(copyDatabase(this)) {
Toast.makeText(this, "Copy database success", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Copy database error", Toast.LENGTH_SHORT).show();
return;
}
}
//Get product list in db when db exists
mPOIList = mDBHelper.getListPOI();
//Init adapter
adapter = new ListPOIadapter(this, mPOIList);
//Set adapter for listview
lvPOI.setAdapter(adapter);
}
private boolean copyDatabase (Context context) {
try {
InputStream inputStream = context.getAssets().open(AmusementPark_Helper.DBNAME);
String outFileName = AmusementPark_Helper.DBLOCATION + AmusementPark_Helper.DBNAME;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[]buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0) {
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.v("Amusement Park", "DB copied");
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
AmusementPark_Helper.java
public class AmusementPark_Helper extends SQLiteOpenHelper {
public static final String DBNAME = "placeofinterest.sqlite";
public static final String DBLOCATION = "/data/data/com.example.lenovo.welcome.ListHelper";
private Context mContext;
private SQLiteDatabase mDatabase;
public AmusementPark_Helper (Context context) {
super(context, DBNAME, null, 1);
this.mContext = context;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public void openDatabase() {
String dbPath = mContext.getDatabasePath(DBNAME).getPath();
if(mDatabase != null && mDatabase.isOpen()) {
return;
}
mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase() {
if(mDatabase != null) {
mDatabase.close();
}
}
public List<DataPOI> getListPOI() {
DataPOI placeofinterest = null;
List<DataPOI> poiList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM amusement_park", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
//below is depends on data type of each column
placeofinterest = new DataPOI(
cursor.getInt(0), cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4), cursor.getString(5),
cursor.getString(6), cursor.getInt(7), cursor.getInt(8),
cursor.getInt(9), cursor.getInt(10), cursor.getInt(11),
cursor.getInt(12), cursor.getInt(13), cursor.getInt(14),
cursor.getString(15), cursor.getBlob(16), cursor.getString(17),
cursor.getString(18), cursor.getString(19), cursor.getString(20));
poiList.add(placeofinterest);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return poiList;
}
}
data_layout.xml (created not by using "create new empty activity")
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="210dp"
android:background="#89cff0">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
app:srcCompat="#mipmap/ic_launcher_round" />
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/imageView"
android:text="Name of POI"
android:textColor="#000"
android:textSize="19sp" />
<TextView
android:id="#+id/operational_hour"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/name"
android:layout_toRightOf="#id/imageView"
android:text="Operational Hours"
android:textColor="#000"
android:textSize="15sp" />
<TextView
android:id="#+id/contact_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/operational_hour"
android:layout_toRightOf="#id/imageView"
android:text="Contact Number"
android:textColor="#000"
android:textSize="15sp" />
<TextView
android:id="#+id/website"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/contact_number"
android:layout_toRightOf="#id/imageView"
android:clickable="true"
android:text="Website"
android:autoLink="web"
android:textColor="#000"
android:textSize="15sp" />
<TextView
android:id="#+id/address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/website"
android:layout_toRightOf="#id/imageView"
android:clickable="true"
android:text="Address"
android:textColor="#000"
android:textSize="15sp" />
<Button
android:id="#+id/button_description"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_below="#id/address"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:layout_toRightOf="#id/imageView"
android:layout_weight="1"
android:background="#drawable/mybutton"
android:text="Description"
android:textColor="#000" />
<Button
android:id="#+id/button_entrance_fee"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_below="#id/address"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:layout_toRightOf="#id/button_description"
android:layout_weight="1"
android:background="#drawable/mybutton"
android:text="Entrance Fee"
android:textColor="#000" />
<Button
android:id="#+id/button_nearest_me"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_below="#id/button_entrance_fee"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:layout_toRightOf="#id/imageView"
android:layout_weight="1"
android:background="#drawable/mybutton"
android:text="Nearest Me"
android:textColor="#000" />
<Button
android:id="#+id/button_take_me_there"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_below="#id/button_entrance_fee"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:layout_toRightOf="#id/button_nearest_me"
android:layout_weight="1"
android:background="#drawable/mybutton"
android:text="Take Me There"
android:textColor="#000" />
</RelativeLayout>
So, how to open new activity from a button which as no .java? I tried to create a new activity and copy paste from the data_layout.xml but it still not working. I hope my explanation is quite clear. and please help me. Thank you.
In your AmusementPark.java file, change
if(false == database.exists()) {
to
if(database.exists == false) {
Also verify the paths are correct. See this very similar article: How do I get a button to open another activity in Android Studio?
Code taken from article:
Manifest file
<activity
android:name="MyOtherActivity"
android:label="#string/app_name">
</activity>
Activity.java file
Button btn = (Button)findViewById(R.id.open_activity_button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, MyOtherActivity.class));
}
});

Recyclview showing data while debug mode but not working in noraml run

I am working on android application and I am facing one problem. When I run my app then nothing showing in recycle view but when i check application in debug mode then data successfully showing in recycle view. I have checked my web service working fine and successfully giving data. How can i achieve this ?
ManageQuestionActivity,java
public class ManageQuestionActivity extends AppCompatActivity implements RecyclerView.OnScrollChangeListener{
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView listView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
private QuestionsListAdapter listAdapter;
private List<QuestionsItem> timeLineItems;
private int requestCount = 1;
private ProgressDialog pDialog;
public static String id, message, token, encodedString;
int pageCount, totalPages;
SQLiteHandler db;
SessionManager session;
ConnectionDetector cd;
EditText edtSearch;
Boolean isInternetPresent = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_question);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
listView = (RecyclerView) findViewById(R.id.list);
edtSearch = (EditText) findViewById(R.id.edtSearch);
listView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
listView.setLayoutManager(layoutManager);
//Adding an scroll change listener to recyclerview
listView.setOnScrollChangeListener(this);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
cd = new ConnectionDetector(this);
isInternetPresent = cd.isConnectingToInternet();
db = new SQLiteHandler(this);
// session manager
session = new SessionManager(this);
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
id = user.get("id");
token = user.get("token");
getData();
timeLineItems = new ArrayList<>();
adapter = new QuestionsListAdapter(timeLineItems, this);
listView.setAdapter(adapter);
}
public void getTimeLineData(final String token, final String page) {
String tag_string_req = "req_register";
// making fresh volley request and getting json
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.questions, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
String message = jObj.getString("message");
if (error) {
totalPages = jObj.getInt("totalPages");
pageCount = jObj.getInt("page");
int limit = jObj.getInt("limit");
parseJsonFeed(response);
}
} catch (Exception e) {
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("page", page);
params.put("limit", "20");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
QuestionsItem item = new QuestionsItem();
item.setId(feedObj.getInt("id"));
item.setQuestion(feedObj.getString("question"));
String options = feedObj.getString("multi_ans_option");
String[] parts = options.split("\\|");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
String part4 = parts[3];
item.setAnsOne(part1);
item.setAnsTwo(part2);
item.setAnsThree(part3);
item.setAnsFour(part4);
item.setAnswer(feedObj.getString("answer"));
timeLineItems.add(item);
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
getTimeLineData(token, String.valueOf(requestCount));
//Incrementing the request counter
requestCount++;
}
//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
#Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//Ifscrolled at last then
if (isLastItemDisplaying(listView)) {
//Calling the method getdata again
getData();
}
}
}
activity_manage_question.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#null" />
</LinearLayout>
QuestionsItem.java
public class QuestionsItem {
private int id;
private String question, ansOne, ansTwo, ansThree, ansFour, answer;
public QuestionsItem() {
}
public QuestionsItem(int id, String question, String ansOne, String ansTwo, String ansThree, String ansFour, String answer) {
super();
this.id = id;
this.question = question;
this.ansOne = ansOne;
this.ansTwo = ansTwo;
this.ansThree = ansThree;
this.ansFour = ansFour;
this.answer = answer;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnsOne() {
return ansOne;
}
public void setAnsOne(String ansOne) {
this.ansOne = ansOne;
}
public String getAnsTwo() {
return ansTwo;
}
public void setAnsTwo(String ansTwo) {
this.ansTwo = ansTwo;
}
public String getAnsThree() {
return ansThree;
}
public void setAnsThree(String ansThree) {
this.ansThree = ansThree;
}
public String getAnsFour() {
return ansFour;
}
public void setAnsFour(String ansFour) {
this.ansFour = ansFour;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
QuestionsListAdapter.java
public class QuestionsListAdapter extends RecyclerView.Adapter<QuestionsListAdapter.ViewHolder> {
private List<QuestionsItem> timeLineItems;
String message, storyId, token, ide;
private Context context;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
ConnectionDetector cd;
Boolean isInternetPresent = false;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
int newPosition;
public QuestionsListAdapter(List<QuestionsItem> timeLineItems, Context context) {
super();
this.context = context;
this.timeLineItems = timeLineItems;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.questios_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
pDialog = new ProgressDialog(context);
pDialog.setCancelable(false);
db = new SQLiteHandler(context);
// session manager
session = new SessionManager(context);
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
token = user.get("token");
//Getting the particular item from the list
QuestionsItem item = timeLineItems.get(position);
holder.txtQues.setText(item.getQuestion());
holder.txtAnsOne.setText(item.getAnsOne());
holder.txtAnsTwo.setText(item.getAnsTwo());
holder.txtAnsThree.setText(item.getAnsThree());
holder.txtAnsFour.setText(item.getAnsFour());
holder.txtAns.setText(item.getAnswer());
holder.btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final QuestionsItem m = timeLineItems.get(position);
String ide = String.valueOf(m.getId());
String ques = String.valueOf(m.getQuestion());
String Option1 = String.valueOf(m.getAnsOne());
String Option2 = String.valueOf(m.getAnsTwo());
String Option3 = String.valueOf(m.getAnsThree());
String Option4 = String.valueOf(m.getAnsFour());
String answer = String.valueOf(m.getAnswer());
Intent intent = new Intent(context, UpdateQuestionActivity.class);
intent.putExtra("id", ide);
intent.putExtra("ques", ques);
intent.putExtra("option1", Option1);
intent.putExtra("option2", Option2);
intent.putExtra("option3", Option3);
intent.putExtra("option4", Option4);
intent.putExtra("answer", answer);
context.startActivity(intent);
}
});
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final QuestionsItem m = timeLineItems.get(position);
newPosition = holder.getAdapterPosition();
ide = String.valueOf(m.getId());
alertBox();
}
});
}
#Override
public int getItemCount() {
return timeLineItems.size();
}
#Override
public int getItemViewType(int position)
{
return position;
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView txtQues, txtAnsOne, txtAnsTwo, txtAnsThree, txtAnsFour, txtAns, btnEdit, btnDelete;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
txtQues = (TextView) itemView.findViewById(R.id.txtQues);
txtAnsOne = (TextView) itemView.findViewById(R.id.txtAnsOne);
txtAnsTwo = (TextView) itemView.findViewById(R.id.txtAnsTwo);
txtAnsThree = (TextView) itemView.findViewById(R.id.txtAnsThree);
txtAnsFour = (TextView) itemView.findViewById(R.id.txtAnsFour);
txtAns = (TextView) itemView.findViewById(R.id.txtAns);
btnEdit = (TextView) itemView.findViewById(R.id.btnEdit);
btnDelete = (TextView) itemView.findViewById(R.id.btnDelete);
}
}
public void alertBox(){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
//Uncomment the below code to Set the message and title from the strings.xml file
//builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);
//Setting message manually and performing action on button click
builder.setMessage("Do you want to delete question ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Check for empty data in the form
cd = new ConnectionDetector(context);
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent){
DeleteQuestion(token, ide);
}else {
final SweetAlertDialog alert = new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE);
alert.setTitleText("No Internet");
alert.setContentText("No connectivity. Please check your internet.");
alert.show();
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
//Creating dialog box
AlertDialog alert = builder.create();
//Setting the title manually
alert.setTitle("Question");
alert.show();
}
private void DeleteQuestion(final String token, final String qid) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Please wait ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.updateQues, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
if (error) {
String errorMsg = jObj.getString("message");
Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
timeLineItems.remove(newPosition);
notifyItemRemoved(newPosition);
notifyItemRangeChanged(newPosition, timeLineItems.size());
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("message");
Toast.makeText(context, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Oops something went wrong...", Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("qid", qid);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
questios_item.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="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp"
android:background="#color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Question : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtQues"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsOne"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsTwo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 3 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsThree"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 4 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsFour"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Answer : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAns"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2">
<TextView android:id="#+id/btnEdit"
android:layout_width="0dp"
android:layout_height="30dp"
android:text="Edit"
android:background="#drawable/rounded_square_comment"
android:gravity="center"
android:textColor="#000000"
android:layout_weight="1"
android:textSize="15sp" />
<TextView
android:id="#+id/btnDelete"
android:layout_width="0dp"
android:layout_height="30dp"
android:text="Delete"
android:background="#drawable/rounded_square_comment"
android:gravity="center"
android:textColor="#000000"
android:layout_weight="1"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
listView.setAdapter should not be here cut
timeLineItems = new ArrayList<>();
adapter = new QuestionsListAdapter(timeLineItems, this);
listView.setAdapter(adapter); // Cut from Here
And paste in this method:
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
QuestionsItem item = new QuestionsItem();
item.setId(feedObj.getInt("id"));
item.setQuestion(feedObj.getString("question"));
String options = feedObj.getString("multi_ans_option");
String[] parts = options.split("\\|");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
String part4 = parts[3];
item.setAnsOne(part1);
item.setAnsTwo(part2);
item.setAnsThree(part3);
item.setAnsFour(part4);
item.setAnswer(feedObj.getString("answer"));
timeLineItems.add(item);
listView.setAdapter(adapter); //Paste Here
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}

How to get values from list and show it in list view android

I am new to android . I have an application working with listview and i want to get data from database and show it in listview.
I have get values and put it in a list ,but having error when getting it from list.
AllOrderDbManager.java
public static List<DetailItem> getDetails(String ordId) { //ordId is the row id
List<DetailItem> data = new ArrayList<>();
String query = AllOrderDbHelper._ID + "=?";
Cursor cursor = database.query(AllOrderDbHelper.TABLE_NAME2, null, query, new String[]{ordId}, null, null, null);
if (cursor != null)
if (cursor.moveToFirst()) {
do {
String food = cursor.getString(cursor.getColumnIndex(FOOD_NAME));
String quantity = cursor.getString(cursor.getColumnIndex(QUANTITY));
DetailItem detailItem = new DetailItem();
detailItem.setFood(food);
detailItem.setQuantity(quantity);
data.add(detailItem);
} while (cursor.moveToNext());
}
cursor.close();
return data;
}
This is my DbManager. Here i am getting values by row id and setting it to a list
DetailItem.java
public class DetailItem {
String food = "";
String quantity = "";
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
#Override
public String toString() {
return food;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private AllOrderDbManager allOrderDbManager;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
allOrderDbManager = new AllOrderDbManager(this);
allOrderDbManager.open();
listView = (ListView) findViewById(R.id.lvDetails);
Intent intent = getIntent();
String ordId = intent.getStringExtra("ordId");
List<DetailItem> values = AllOrderDbManager.getDetails(ordId);
for (DetailItem detailItem: values) {
String food_name = detailItem.getFood();
String quantity = detailItem.getQuantity();
}
String[] from = new String[] {food_name, quantity};
int[] to = new int[] {R.id.tvItemsName, R.id.tvQuantity};
SimpleAdapter adapter = new SimpleAdapter(this,values,
R.layout.all_order_details_list, from, to);
listView.setAdapter(adapter);
}
}
Here i can't get values from list and set it to listview.
activity_main.xml
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" >
<ListView
android:id="#+id/lvDetails"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
all_order_details_list
<TextView
android:id="#+id/tvItemsName"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textStyle="bold"
android:textColor="#android:color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/tvQuantity"
android:layout_width="0dip"
android:textStyle="bold"
android:gravity="center"
android:textSize="15sp"
android:textColor="#android:color/black"
android:layout_height="match_parent"
android:layout_weight="1"/>
please help.
I have solved it using HashMap.
public class MainActivity extends AppCompatActivity {
private AllOrderDbManager allOrderDbManager;
private ListView listView;
static final String FOODNAME = "foodName";
static final String QTY = "quantity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
allOrderDbManager = new AllOrderDbManager(this);
allOrderDbManager.open();
listView = (ListView) findViewById(R.id.lvDetails);
Intent intent = getIntent();
String ordId = intent.getStringExtra("ordId");
String[] from = new String[] {"foodName","quantity"};
int[] to = new int[] {R.id.tvItemsName, R.id.tvQuantity};
List<DetailItem> values = AllOrderDbManager.getDetails(ordId);
ArrayList<HashMap<String, String>> test = new ArrayList<HashMap<String, String>>();
for (DetailItem detailItem: values) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(FOODNAME,(String)detailItem.getFood());
map.put(QTY,(String)detailItem.getQuantity());
test.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(this, test, R.layout.all_order_details_list, from, to);
listView.setAdapter(adapter);
}
Thanku

Retrieve result through REST API and show it in a LIST VIEW in a new activity (Minor issue arises with LIST VIEW)

I am retrieving data from a JOB site through REST api. I am able to retrieve the data and even can show that in the same page after Search button. But, I want to show the list view in the new activity . I am using Intent to do this. But, Unfortunately, I am unable to show that. My app crashes and outputs nothing, once I click on it.
MAIN ACTIVITY.java
public class MainActivity extends Activity {
//private String url1 = "http://api.openweathermap.org/data/2.5/weather?q=";
//private String url2 = "&mode=xml";
EditText queryText;
EditText locationText;
EditText sortText;
EditText fromAgeText;
ListView responseView;
// EditText radiusText;
ProgressBar progressBar;
EditText jtText;
EditText chnlText;
EditText countryText;
EditText txText;
static final String API_KEY = "298**70********4";
static final String API_URL = "http://api.xyz.com/abc/apisearch?";
ProgressDialog waitProgress;
EditText startText;
EditText limitRes;
EditText filterText;
EditText userIpText; //="122.171.57.131";
EditText radiusText;
EditText browserText;
EditText version;
EditText stText;
EditText latlongText;
//private HandleXML obj;
String finalUrl;
ArrayList<Result> rList = null;
ArrayList<Result> resultlist;
String tempResponse;
private PostBaseAdapter adapter;
ListView list;
Result result;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializeUI("java","bangalore","karnataka","date","25","jobsite","fulltime","0","15","14","1","1","india","null","122.172.176.113","chrome","2");
initializeUI();
}
//responseView = (ListView) findViewById(R.id.responseView);
private void initializeUI() {
queryText = (EditText) findViewById(R.id.queryText);
locationText = (EditText) findViewById(R.id.locationText);
txText = (EditText) findViewById(R.id.txText);
sortText = (EditText) findViewById(R.id.sortText);
radiusText = (EditText) findViewById(R.id.radiusText);
stText = (EditText) findViewById(R.id.stText);
jtText = (EditText) findViewById(R.id.jtText);
//startText = (EditText) findViewById(R.id.startText);
limitRes = (EditText) findViewById(R.id.limitRes);
fromAgeText = (EditText) findViewById(R.id.fromAgeText);
//filterText = (EditText) findViewById(R.id.filterText);
//latlongText = (EditText) findViewById(R.id.latlongText);
countryText = (EditText) findViewById(R.id.countryText);
//chnlText = (EditText) findViewById(R.id.chnlText);
userIpText = (EditText) findViewById(R.id.userIpText);
//browserText = (EditText) findViewById(R.id.browserText);
//version = (EditText) findViewById(R.id.version);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
Button queryButton = (Button) findViewById(R.id.queryButton);
//list = (ListView) findViewById(R.id.resultList);
queryButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String query = queryText.getText().toString();
String location = locationText.getText().toString();
String tx = txText.getText().toString();
String sort = sortText.getText().toString();
String radius = radiusText.getText().toString();
String st = stText.getText().toString();
String jobtype = jtText.getText().toString();
//String start = startText.getText().toString();
String limit = limitRes.getText().toString();
String fromAge = fromAgeText.getText().toString();
//String filter = filterText.getText().toString();
//String latlong = latlongText.getText().toString();
String country = countryText.getText().toString();
//String chnlTxt = chnlText.getText().toString();
String userIp = userIpText.getText().toString();
//String browser = browserText.getText().toString();
//String versionTx = version.getText().toString();
//ArrayList<String> arl= new ArrayList<String>();
//arl.add(query);
new RetrieveFeedTask().execute(query, location, tx, sort, radius, st, jobtype,"1",limit,fromAge,"1","1",country,"null",userIp, "chrome","2");
//responseView.setText(url);
Log.e("ERROR","In button call");
Log.i("INFO","Inside Button call");
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.tvTitle)).getText().toString();
// create intent to start another activity
Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(resultlist.get(position).getJobtitle()));
// add the selected text item to our intent.
intent.putExtra("title", name);
startActivity(intent);
}
});
}
class RetrieveFeedTask extends AsyncTask<String, String, String> {
private Exception exception;
String tempResponse = "";
protected void onPreExecute() {
waitProgress = ProgressDialog.show(MainActivity.this, "", "Loading... please wait...");
// progressBar.setVisibility(View.VISIBLE);
// responseView.setAdapter(null);//.setText(" ");
Log.e("ERROR","In onPreExecute call");
Log.i("INFO","Inside onPreExecutecall");
}
protected String doInBackground(String... args) {
// Do some validation here
String query = args[0];
String location = args[1];
String tx = args[2];
String sort = args[3];
String radius = args[4];
String st = args[5];
String jobtype = args[6];
String start = args[7];
String limit = args[8];
String fromAge = args[9];
String filter = args[10];
String latlong = args[11];
String country = args[12];
String chnlTxt = args[13];
String userIp = args[14];
String browser = args[15];
String versionTx = args[16];
finalUrl = API_URL + "publisher=" + API_KEY + "&q=" + query + "&l=" + location + "," + tx + "&sort=" + sort + "&radius=" + radius + "&st=" + st + "&jt=" + jobtype + "&start=" + start + "&limit=" + limit + "&fromage=" + fromAge + "&filter=" + filter + "&latlong=" + latlong + "&co=" + country + "&chnl=" + chnlTxt + "&userip=" + userIp + "&useragent=" + browser + "&v=" + versionTx;
//finalUrl= "http://api.xyz.com/ads/apisearch?publisher=2986470692413324&q=java&l=BANGALORE%2C+karnataka&sort=date&radius=25&st=jobsite&jt=fulltime&start=1&limit=10&fromage=14&filter=1&latlong=1&co=india&chnl=null&userip=122.166.158.225&useragent=Chrome&v=2";
SAXParser();
return "";
}
protected void onPostExecute(String response) {
/* if (response == null || response.trim().equals("")) {
response = "THERE WAS AN ERROR";
}*/
/* if (rList == null) {
responseView.setAdapter(null); //setText("Error");
//return;
}*/
// progressBar.setVisibility(View.GONE);
//Log.i("INFO", response);
// getting values from selected ListItem
// Bundle bundle= new Bundle();
String name = ((TextView) findViewById(R.id.tvTitle)).getText().toString();
Bundle bundle= new Bundle();
// create intent to start another activity
//bundle.putString("name",result.getJobtitle());
Intent intent2 = new Intent(MainActivity.this, ResultListView.class);
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(resultlist.get(position).getJobtitle()));
// add the selected text item to our intent.
//intent2.putExtra("title", name);
bundle.putString("title",name);
intent2.putExtra("pBundle",bundle);
startActivity(intent2);
//displayData();
if (waitProgress != null) {
waitProgress.dismiss();
}
}
/* protected void onPostExecute()
{ progressBar.setVisibility(View.GONE);
displayData();
}*/
private void SAXParser(){
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
// create a parser
//XMLReader xmlreader = factory.getXMLReader();
SAXParser parser = factory.newSAXParser();
resultlist = new ArrayList<Result>();
URL ul = new URL(finalUrl);
URLConnection uc = ul.openConnection();
ResultHandler resultHandler = new ResultHandler(resultlist);
// assign our handler
// xmlreader.setContentHandler(resultHandler);
// perform the synchronous parse
parser.parse(new InputSource(uc.getInputStream()), resultHandler);
resultlist = resultHandler.getResultList();
Log.e("ERROR","In SAXParser call");
Log.i("INFO","Inside SAXParser");
} catch (Exception e) {
e.printStackTrace();
}
Log.e("ERROR","In doInBackground call");
Log.i("INFO","Inside doInBackgr call");
// SAXParser();
}
}
activity_main.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:fillViewport="true"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="portfolio.first_app.practice.com.simplewebapi3.xyzJobActivity">
<EditText
android:id="#+id/queryText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Skill"/>
<!--android:inputType="textEmailAddress"-->
<EditText
android:id="#+id/locationText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Location"/>
<EditText
android:id="#+id/txText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the State"/>
<EditText
android:id="#+id/sortText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Date"/>
<EditText
android:id="#+id/radiusText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Radius"/>
<EditText
android:id="#+id/stText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Site Type"/>
<EditText
android:id="#+id/jtText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Job Type"/>
<!-- <EditText
android:id="#+id/startText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Start Index of the Result"/>-->
<EditText
android:id="#+id/limitRes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Result Limit"/>
<EditText
android:id="#+id/fromAgeText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Age"/>
<!-- <EditText
android:id="#+id/filterText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Duplicate filter value"/>
<EditText
android:id="#+id/latlongText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the value 1 or 0"/>-->
<EditText
android:id="#+id/countryText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Country"/>
<!-- <EditText
android:id="#+id/chnlText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Group channel"/>-->
<EditText
android:id="#+id/userIpText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the User IP address"/>
<!-- <EditText
android:id="#+id/browserText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Browser"/>
<EditText
android:id="#+id/version"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Version:"/>-->
<Button
android:id="#+id/queryButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
style="#style/Base.Widget.AppCompat.Button.Borderless"
android:text="Search"/>
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"
android:layout_centerHorizontal="true"
android:visibility="gone" />
</LinearLayout>
</ScrollView>
ResultListView.java
/**
* Created by SouRAV on 6/15/2016.
*/
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by SouRAV on 6/15/2016.
*/
public class ResultListView extends Activity {
TextView textView;
ListView list;
ArrayList<Result> resultlist;
private PostBaseAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_list_view);
list = (ListView) findViewById(R.id.resultList);
textView = (TextView) findViewById(R.id.textView);
// get the intent from which this activity is called.
Intent intent2 = getIntent();
Bundle bundle= intent2.getBundleExtra("pBundle");
String text = bundle.getString("title");
textView.setText(text);
displayData1();
// fetch value from key-value pair and make it visible on TextView.
//Bundle intent2 = getIntent().getExtras();
//String list_data = intent2.getString("list");
// textView.setText(list_data);
}
private void displayData1() {
adapter = new PostBaseAdapter(ResultListView.this, resultlist);
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
Log.e("ERROR","In displayData call");
Log.i("Info","Inside displaydata");
//Log.i("INFO", response);
// responseView.setText(response);
// ProgressBar.dismiss();
}
}
result_list_view.xml
<LinearLayout android:layout_height="wrap_content"
android:layout_width="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android" >
<ListView android:id="#+id/resultList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
</ListView>
</LinearLayout>
Result.java
package portfolio.first_app.practice.com.xyzjobactivity3;
/**
* Created by SouRAV on 4/29/2016.
*/
import java.util.ArrayList;
import java.util.ArrayList;
public class Result {
public String jobtitle;
public String company;
public String city;
public String state;
public String country;
public String formattedLocation;
public String source;
public String date;
public String snippet;
public String url;
public String onmousedown;
public String lattitude;
public String longitude;
public String jobkey;
public String sponsored;
public String expired;
public String formattedLocationFull;
public String formattedRelativeTime;
public String getJobtitle() {
return jobtitle;
}
public void setJobtitle(String jobtitle) {
this.jobtitle = jobtitle;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getFormattedLocation() {
return formattedLocation;
}
public void setFormattedLocation(String formattedLocation) {
this.formattedLocation = formattedLocation;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSnippet() {
return snippet;
}
public void setSnippet(String snippet) {
this.snippet = snippet;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getOnmousedown() {
return onmousedown;
}
public void setOnmousedown(String onmousedown) {
this.onmousedown = onmousedown;
}
public String getLattitude() {
return lattitude;
}
public void setLattitude(String lattitude) {
this.lattitude = lattitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getJobkey() {
return jobkey;
}
public void setJobkey(String jobkey) {
this.jobkey = jobkey;
}
public String getSponsored() {
return sponsored;
}
public void setSponsored(String sponsored) {
this.sponsored = sponsored;
}
public String getExpired() {
return expired;
}
public void setExpired(String expired) {
this.expired = expired;
}
public String getFormattedLocationFull() {
return formattedLocationFull;
}
public void setFormattedLocationFull(String formattedLocationFull) {
this.formattedLocationFull = formattedLocationFull;
}
public String getFormattedRelativeTime() {
return formattedRelativeTime;
}
public void setFormattedRelativeTime(String formattedRelativeTime) {
this.formattedRelativeTime = formattedRelativeTime;
}
public String getDetails() {
String result = jobtitle + ": " + company + "\n" + city + "-" + state
+ "\n" + country + "\n" + formattedLocation +"\n" + source+"\n"+date+
"\n"+snippet+"\n"+url+"\n"+onmousedown+"\n"+lattitude+"\n"+longitude+"\n"
+jobkey+"\n"+sponsored+"\n"+expired+"\n"+formattedLocationFull+"\n"+formattedRelativeTime;
return result;
}
}
I am not showing PARSING XML data as it is working fine. Issue is simple , I am using intent, but unable to display it in LIST VIEW. I am asking about the code inside postExecute();
Implement Result by Parcelable interface. Now after fetchind data from server, just put the ArrayList in intent, and retrieve them in ResultActivity.
In list.setItemClickListener -
Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
intent.putParcelableArrayListExtra("RESULT", resultlist);
intent.putExtra("title", name);
startActivity(intent);
And again in onCreate of Result activity don't forget to initialize resultlist -
resultlist = getIntent().getParcelableArrayExtra("RESULT");
Hope it will help you :)

Categories

Resources