cannot resolve symbol HorizontalListView - java

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...).

Related

Toast On ArrayAdapter

Toast On ArrayAdapter
How to Show Toast message On QuoteArrayAdapter OnClick textViewQuoteLike
Show message Like is Done
public static ViewHolder create(RelativeLayout rootView) {
ImageView imageViewProfilePhoto = (ImageView) rootView.findViewById(R.id.imageViewProfilePhoto);
TextView textViewQuoteContent = (TextView) rootView.findViewById(R.id.textViewQuoteContent);
TextView textViewProfileName = (TextView) rootView.findViewById(R.id.textViewProfileName);
final TextView textViewQuoteLike = (TextView) rootView.findViewById(R.id.textViewQuoteLike);
TextView textViewQuoteCopy = (TextView) rootView.findViewById(R.id.textViewQuoteCopy);
TextView textViewQuoteShare = (TextView) rootView.findViewById(R.id.textViewQuoteShare);
final TextView textViewQuoteId = (TextView) rootView.findViewById(R.id.textViewQuoteId);
textViewQuoteLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new GetDataLike().execute(textViewQuoteId.getText().toString());
String currentLike = textViewQuoteLike.getText().toString();
currentLike = currentLike.replace("پسندیدم (","");;
currentLike = currentLike.replace(")","");;
int newLike = Integer.valueOf(currentLike.toString()) + 1;
textViewQuoteLike.setText("پسندیدم ("+newLike+")");
/*Toast.makeText(Need Activity, "Like is done.",
Toast.LENGTH_LONG).show();*/
}
});
return new ViewHolder(rootView, imageViewProfilePhoto, textViewQuoteContent, textViewProfileName, textViewQuoteLike, textViewQuoteCopy, textViewQuoteShare, textViewQuoteId);
}
If there is a way that in HomeFragment Put it, Please give an example
QuoteArrayAdapter.java
package com.example.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.R;
import com.example.model.QuoteDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
public class QuoteArrayAdapter extends ArrayAdapter<QuoteDataModel> {
List<QuoteDataModel> modelList;
Context context;
private LayoutInflater mInflater;
// Constructors
public QuoteArrayAdapter(Context context, List<QuoteDataModel> objects) {
super(context, 0, objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
modelList = objects;
}
#Override
public QuoteDataModel getItem(int position) {
return modelList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder vh;
if (convertView == null) {
View view = mInflater.inflate(R.layout.quote_row, parent, false);
vh = ViewHolder.create((RelativeLayout) view);
view.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
QuoteDataModel item = getItem(position);
vh.textViewQuoteContent.setText(item.getQuoteContent());
vh.textViewProfileName.setText(item.getProfileName());
vh.textViewQuoteLike.setText("پسندیدم ("+item.getQuoteLike()+")");
vh.textViewQuoteCopy.setText("کپی کردن");
vh.textViewQuoteShare.setText("اشتراک گزاری");
vh.textViewQuoteId.setText(item.getQuoteId());
Picasso.with(context).load(item.getProfilePhoto()).placeholder(R.drawable.empty_profile_photo).error(R.drawable.empty_profile_photo).transform(new CircleTransform()).into(vh.imageViewProfilePhoto);
return vh.rootView;
}
private static class ViewHolder {
public final RelativeLayout rootView;
public final ImageView imageViewProfilePhoto;
public final TextView textViewQuoteContent;
public final TextView textViewProfileName;
public final TextView textViewQuoteLike;
public final TextView textViewQuoteCopy;
public final TextView textViewQuoteShare;
public final TextView textViewQuoteId;
private ViewHolder(RelativeLayout rootView, ImageView imageViewProfilePhoto, TextView textViewQuoteContent, TextView textViewProfileName, TextView textViewQuoteLike, TextView textViewQuoteCopy, TextView textViewQuoteShare, TextView textViewQuoteId) {
this.rootView = rootView;
this.imageViewProfilePhoto = imageViewProfilePhoto;
this.textViewQuoteContent = textViewQuoteContent;
this.textViewProfileName = textViewProfileName;
this.textViewQuoteLike = textViewQuoteLike;
this.textViewQuoteCopy = textViewQuoteCopy;
this.textViewQuoteShare = textViewQuoteShare;
this.textViewQuoteId = textViewQuoteId;
}
public static ViewHolder create(RelativeLayout rootView) {
ImageView imageViewProfilePhoto = (ImageView) rootView.findViewById(R.id.imageViewProfilePhoto);
TextView textViewQuoteContent = (TextView) rootView.findViewById(R.id.textViewQuoteContent);
TextView textViewProfileName = (TextView) rootView.findViewById(R.id.textViewProfileName);
final TextView textViewQuoteLike = (TextView) rootView.findViewById(R.id.textViewQuoteLike);
TextView textViewQuoteCopy = (TextView) rootView.findViewById(R.id.textViewQuoteCopy);
TextView textViewQuoteShare = (TextView) rootView.findViewById(R.id.textViewQuoteShare);
final TextView textViewQuoteId = (TextView) rootView.findViewById(R.id.textViewQuoteId);
textViewQuoteLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new GetDataLike().execute(textViewQuoteId.getText().toString());
String currentLike = textViewQuoteLike.getText().toString();
currentLike = currentLike.replace("پسندیدم (","");;
currentLike = currentLike.replace(")","");;
int newLike = Integer.valueOf(currentLike.toString()) + 1;
textViewQuoteLike.setText("پسندیدم ("+newLike+")");
}
});
return new ViewHolder(rootView, imageViewProfilePhoto, textViewQuoteContent, textViewProfileName, textViewQuoteLike, textViewQuoteCopy, textViewQuoteShare, textViewQuoteId);
}
}
static class GetDataLike extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Nullable
#Override
protected String doInBackground(String... params) {
String quoteId = params[0];
JSONObject jsonObject = JSONParser.getDataFromWeb("http://example.com/api-service/v1/platform_quote_like/?platform=true&id="+quoteId);
try {
if (jsonObject != null) {
if(jsonObject.length() > 0) {
JSONArray array = jsonObject.getJSONArray(Keys.KEY_LIKE);
int lenArray = array.length();
if(lenArray > 0) {
for(int jIndex = 0; jIndex < lenArray; jIndex++) {
JSONObject innerObject = array.getJSONObject(jIndex);
String quote_like = innerObject.getString(Keys.KEY_QUOTE_LIKE);
return quote_like;
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
}
}
public class CircleTransform implements Transformation {
#Override
public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
if (squaredBitmap != source) {
source.recycle();
}
Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
BitmapShader shader = new BitmapShader(squaredBitmap,
BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
paint.setShader(shader);
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
squaredBitmap.recycle();
return bitmap;
}
#Override
public String key() {
return "circle";
}
}
}
HomeFragment.java
package com.example;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.adapter.QuoteArrayAdapter;
import com.example.model.QuoteDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class HomeFragment extends Fragment {
private ListView listView;
private ArrayList<QuoteDataModel> list;
private QuoteArrayAdapter adapter;
private TextView likeCurrent;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_home, null);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
/**
* Array List for Binding Data from JSON to this List
*/
list = new ArrayList<>();
adapter = new QuoteArrayAdapter(getActivity(), list);
/**
* Getting List and Setting List Adapter
*/
listView = (ListView) getActivity().findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Snackbar.make(getActivity().findViewById(R.id.parentLayout), list.get(position).getProfileName() + " => " + list.get(position).getQuoteLike(), Snackbar.LENGTH_LONG).show();
}
});
/**
* Check internet connection
*/
if (!MainActivity.NetworkUtil.isOnline(getActivity().getApplicationContext())) {
Toast.makeText(getActivity(), "اتصال به اینترنت برقرار نیست",
Toast.LENGTH_LONG).show();
}
new GetDataHome().execute();
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
{
new GetDataHome().execute();
}
}
});
/*
likeCurrent = (TextView) getActivity().findViewById(R.id.textViewQuoteLike);
likeCurrent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
likeCurrent.setText("Boiling Point K");
}
});*/
}
/**
* Creating Get Data Task for Getting Data From Web
*/
class GetDataHome extends AsyncTask<Void, Void, Void> {
ContentLoadingProgressBar progressBar;
#Override
protected void onPreExecute() {
super.onPreExecute();
/**
* Progress Bar for User Interaction
*/
progressBar = (ContentLoadingProgressBar) getActivity().findViewById(R.id.progress);
progressBar.show();
}
#Nullable
#Override
protected Void doInBackground(Void... params) {
/**
* Getting JSON Object from Web Using okHttp
*/
JSONObject jsonObject = JSONParser.getDataFromWeb("http://example.com/api-service/v1/platform_home/?platform=true");
try {
/**
* Check Whether Its NULL???
*/
if (jsonObject != null) {
/**
* Check Length...
*/
if(jsonObject.length() > 0) {
/**
* Getting Array named "Home" From MAIN Json Object
*/
JSONArray array = jsonObject.getJSONArray(Keys.KEY_HOME);
/**
* Check Length of Array...
*/
int lenArray = array.length();
if(lenArray > 0) {
for(int jIndex = 0; jIndex < lenArray; jIndex++) {
/**
* Creating Every time New Object
* and
* Adding into List
*/
QuoteDataModel model = new QuoteDataModel();
/**
* Getting Inner Object from contacts array...
* and
* From that We will get Name of that Contact
*
*/
JSONObject innerObject = array.getJSONObject(jIndex);
String profile_photo = innerObject.getString(Keys.KEY_PROFILE_PHOTO);
String profile_name = innerObject.getString(Keys.KEY_PROFILE_NAME);
String profile_link = innerObject.getString(Keys.KEY_PROFILE_LINK);
String quote_like = innerObject.getString(Keys.KEY_QUOTE_LIKE);
String quote_id = innerObject.getString(Keys.KEY_QUOTE_ID);
String quote_content = innerObject.getString(Keys.KEY_QUOTE_CONTENT);
String quote_category = innerObject.getString(Keys.KEY_QUOTE_CATEGORY);
/**
* Getting Object from Object "other"
*/
//JSONObject otherObject = innerObject.getJSONObject(Keys.KEY_NAME);
//String other = otherObject.getString(Keys.KEY_NAME_SUB);
model.setProfilePhoto(profile_photo);
model.setProfileName(profile_name);
model.setProfileLink(profile_link);
model.setQuoteLike(quote_like);
model.setQuoteId(quote_id);
model.setQuoteContent(quote_content);
model.setQuoteCategory(quote_category);
/**
* Adding data in List...
*/
list.add(model);
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
/**
* Progress Bar for User Interaction
*/
progressBar.hide();
/**
* Checking if List size if more than zero then
* Update ListView
*/
if(list.size() > 0) {
adapter.notifyDataSetChanged();
} else {
Snackbar.make(getActivity().findViewById(R.id.parentLayout), "مشکلی در اتصال به سرورهای سخنک رخ داده است!", Snackbar.LENGTH_LONG).show();
}
}
}
}
quote_row.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="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/imageViewProfilePhoto"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="5dp"
android:layout_gravity="right"
android:layout_alignParentRight="true"
android:src="#drawable/empty_profile_photo" />
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_centerVertical="true"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/imageViewProfilePhoto">
<TextView
android:id="#+id/textViewQuoteContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
android:textIsSelectable="true"
tools:text="Quote Content" />
<TextView
android:id="#+id/textViewProfileName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
android:textIsSelectable="true"
tools:text="Profile Name" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/textViewQuoteCopy"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
android:clickable="true"
tools:text="Copy" />
<TextView
android:id="#+id/textViewQuoteShare"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
tools:text="Share" />
<TextView
android:id="#+id/textViewQuoteLike"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
tools:text="Like" />
</LinearLayout>
</LinearLayout>
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/textViewQuoteId"
android:visibility="invisible" />
</RelativeLayout>
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/parentLayout"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible" />
<ListView app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/listView"
android:layout_width="fill_parent"
android:layout_height="match_parent" />
</RelativeLayout>
You just need a context, so:
Toast.makeText(rootView.getContext(), "Like is done.",
Toast.LENGTH_LONG).show();
But you need to make rootView final first:
public static ViewHolder create(final RelativeLayout rootView){...
^^

how to increase and decrease value(number of qty.)with ImageView?

I want to Increase and decrease value of qty on clicked.
i Used ImageView for decrease and Increase the value in middle i used TextView for showing the value.
this thing is completely work in the Activity but i want perform this operation in ListView.
Here the complete code and it is working on simple Activity.
qty.java
public class qty extends AppCompatActivity {
int minteger = 0;
ImageView decrease;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.raw_order);
decrease=(ImageView) findViewById(R.id.decrease);
decrease.setEnabled(false);
}
public void increaseInteger(View view) {
minteger = minteger + 1;
display(minteger);
}public void decreaseInteger(View view) {
minteger = minteger - 1;
display(minteger);
}
private void display(int number) {
TextView displayInteger = (TextView) findViewById(
R.id.integer_number);
displayInteger.setText("" + number);
}
}
raw_order.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/decrease"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:src="#drawable/minus"
android:layout_marginTop="05dp"
android:textColor="#000"
android:onClick="decreaseInteger"
/>
<TextView
android:id="#+id/integer_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:textStyle="bold"
android:layout_marginTop="16dp"
android:textSize="20dp" />
<ImageView
android:id="#+id/increase"
android:layout_marginTop="05dp"
android:layout_width="30dp"
android:onClick="increaseInteger"
android:layout_height="wrap_content"
android:src="#drawable/plus"
android:textColor="#000"/>
</LinearLayout>
And i want to perform this same thing in ListView
ListViewadapterorder.java
package omcommunication.orderdesign;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static android.media.CamcorderProfile.get;
public class ListViewAdapterorder extends BaseAdapter implements ListAdapter{
Context cntx;
SparseIntarray sia; // class variable
// SessionManager session;
AlertDialog.Builder alertDialogBuilder;
View view;
int minteger = 0;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
private boolean status;
public static final String KEY_EMP_ID = "id";
public static final String TAG_ID = "o_id";
ArrayList<String> o_aid = new ArrayList<String>();
ArrayList<String> o_aproduct = new ArrayList<String>();
ArrayList<String> o_aqty = new ArrayList<String>();
ArrayList<String> o_atotal = new ArrayList<String>();
public ListViewAdapterorder(Context context,
ArrayList<String> o_id,
ArrayList<String> o_product,
ArrayList<String> o_qty,
ArrayList<String> o_total
) {
// TODO Auto-generated constructor stub
cntx = context;
o_aid = o_id;
o_aproduct = o_product;
o_aqty = o_qty;
o_atotal = o_total;
alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setMessage("Do You Want To Call....");
/* session = new SessionManager(context);
HashMap<String, String> user = session.getUserDetails();
uid = user.get(SessionManager.KEY_ID);
*/
}
#Override
public int getCount() {
return o_aid.size();
}
#Override
public Object getItem(int position) {
return o_aid.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
TextView mname , pmethod2, pamount3, premark4;
final ImageView increase,decrease;
final TextView displayInteger;
inflater = (LayoutInflater) cntx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = LayoutInflater.from(cntx);
convertView = inflater.inflate(R.layout.raw_order, parent,
false);
decrease = (ImageView) convertView.findViewById(R.id.decrease);
increase= (ImageView) convertView.findViewById(R.id.increase);
mname = (TextView) convertView.findViewById(R.id.mname);
mname.setText(" " + o_aproduct.get(position));
sia = new SparseIntarray(data.size());
displayInteger = (TextView) convertView.findViewById(R.id.integer_number);
increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int count = sia.get(position);
count++;
resultp.put(cout);
displayInteger.setText("" + count);
}
});
return convertView;
}
private class SparseIntarray {
public SparseIntarray(int size) {
}
}
}
you can use SparseIntArray to store the value count for each position
in the listAdapter class define an instance variable
SparseIntArray sia; // class variable
.. inside listAdapter constructor
sia = new SparseIntArray(data.size());
then in OnClick event
public void onItemClick(...) {
int count = sia.get(position)
// now increment or decrement as per your requirement
// coutn++; or count--; and save it
sia.put(position, count);
Edit 1:
set OnClick listeners to your increase decrease imageViews in the getView() method,
final displayInteger = (TextView) convertView.findViewById(R.id.integer_number);
increase.setOnClikcListener(new OnClickListener {
#Override
public void onClick(View view)
{
int count = sia.get(position);
count++;
sia.put(position, count);
displayInteger.setText("" + count);
});
you can do the same with your decrease view
Make an OnLickListener for the image view and call the methods,
For the list view you need to make an OnItemSelectedListener Or OnItemClickListener
First You Need To Give The ImageView an ID; Then Do It Like This
In On Create :::
ImageView img=(ImageView)findViewById(R.id.imageview);
img.setOnClickListener(imgclick);
Then In The Class Body ::::
OnClickListener imgclick=new OnClickListener() {
#Override
public void onClick(View view) {
//Call The Methods Like Increase Number Or Decrease
}
};

Date picker from SwipeStackAdapter adapter

I have googled alot. But i did't get the solution.
My issue is i have one fragment. In the fragment i am inflating some cards ie the swipe cards. for that swipe cards layout im using SwipeStackAdapter to inflate the view xml.
The in one of my xml view im trying to implement the datepicker.
TaskCardListShow.java fragment code
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v7.app.AppCompatActivity;
import com.jmedeisis.draglinearlayout.DragLinearLayout;
import java.util.ArrayList;
import java.util.List;
import link.fls.swipestack.SwipeStack;
public class TaskCardListShow extends Fragment implements SwipeStack.SwipeStackListener, View.OnClickListener {
private ArrayList<String> mData;
private ArrayList<String> LayOutData;
private SwipeStack mSwipeStack;
private SwipeStackAdapter mAdapter;
public int cardCounter;
Context context;
AutoCompleteTextView autoTextView;
public TaskCardListShow() {
}
public static TaskCardListShow newInstance() {
TaskCardListShow _TaskCardListShow = new TaskCardListShow();
return _TaskCardListShow;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.task_card_list_show, container, false);
mSwipeStack = (SwipeStack) view.findViewById(R.id.swipeStack);
mData = new ArrayList<>();
LayOutData = new ArrayList<>();
mAdapter = new SwipeStackAdapter(mData,LayOutData);
mSwipeStack.setAdapter(mAdapter);
mSwipeStack.setListener(this);
context=getActivity().getApplicationContext();
cardCounter=7;// write function for getting card count.
fillStackCard();
return view;
}
private void fillStackCard() {
for (int x = 0; x <cardCounter; x++) {
mData.add(getString(R.string.dummy_text) + " " + (x + 1));
LayOutData.add(getString(R.string.str_card)+ (x + 1));
}
}
#Override
public void onClick(View v) {
}
#Override
public void onViewSwipedToRight(int position) {
String swipedElement = mAdapter.getItem(position);
}
#Override
public void onViewSwipedToLeft(int position) {
String swipedElement = mAdapter.getItem(position);
}
#Override
public void onStackEmpty() {
removeTaskCardFragment();
}
public void removeTaskCardFragment(){
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction mFragmentTransaction = manager.beginTransaction();
TaskCardListShow _TaskCardListShowFragment = new TaskCardListShow();
mFragmentTransaction.remove(_TaskCardListShowFragment);
mFragmentTransaction.commit();
manager.popBackStack();
}
public class SwipeStackAdapter extends BaseAdapter {
private List<String> mData;
private List<String> LayOutData;
DragLinearLayout dragDropAndroidLinearLayout;
public SwipeStackAdapter(List<String> data,List<String> Ldata) {
this.mData = data;
this.LayOutData = Ldata;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
String LName=LayOutData.get(position);
try {
int id = getActivity().getApplicationContext().getResources().
getIdentifier(LName, "layout", getActivity().getPackageName());
convertView = getActivity().getLayoutInflater().inflate(id, parent, false);
if(position==4){ // my date picker layout will come this postion.
}
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
}
card_4.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:layout_width="match_parent"
card_view:cardCornerRadius="#dimen/card_corner_radius"
card_view:cardElevation="#dimen/elevation_large"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center"
android:id="#+id/TxtQuestion">
<TextView
android:id="#+id/textViewCard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="top"
android:textColor="#color/colorAccent"
android:textStyle="bold|italic"
android:textSize="20sp"
android:padding="30dp"
android:layout_gravity="top|center_horizontal|center_vertical"
android:text="Date picker template"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_below="#+id/TxtQuestion"
android:layout_centerInParent="true"
android:id="#+id/linearLayout">
<DatePicker
android:id="#+id/dpResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
Can you please guide me to do this. I have tried lots of method but it is not working i my case
I have solved my problem by,
in my adapter
final TextView _dpResult=(TextView)convertView.findViewById(R.id.dpResult);
_dpResult.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
DialogFragment newFragment = new SelectDateFragment( );
newFragment.show(getFragmentManager(), "DatePicker");
}
});
SelectDateFragment
public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
public void onDateSet(DatePicker view, int yy, int mm, int dd) {
populateSetDate(yy, mm+1, dd);
}
public void populateSetDate(int year, int month, int day) {
TextView dpResult= (TextView)getActivity().findViewById(R.id.dpResult);
dpResult.setText(year+"-"+month+"-"+day);
}
}
The xml coding for the date picker is
<TextView
android:id="#+id/dpResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="yyyy-mm-dd" />
Now i am able see the date-picker on my card. Thanks

data is not visible in listview

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.

Android ListView not being populated by custom ParseQueryAdapter

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");

Categories