AndroidPieChart will not show - android

This is my XML :
<net.kenyang.piechart.PieChart
android:id="#+id/pieChart"
android:layout_below="#id/id_bar"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
This is the code that I use for the piechart to be initialised:
ArrayList<PieChartData> alPercentage = new ArrayList<PieChartData>();
alPercentage.add(new PieChartData(55.0f, "1"));
alPercentage.add(new PieChartData(45.0f, "2"));
try {
// setting data
pieChart.setAdapter(alPercentage);
// setting a listener
pieChart.setOnSelectedListener(new PieChart.OnSelectedLisenter() {
#Override
public void onSelected(int iSelectedIndex) {
Toast.makeText(PSTravelStatisticsActivity.this, "Select index:" + iSelectedIndex, Toast.LENGTH_SHORT).show();
}
});
pieChart.setVisibility(View.VISIBLE);
pieChart.invalidate();
} catch (Exception e) {
Log.i("","error is : " + e.getMessage());
if (e.getMessage().equals(PieChart.ERROR_NOT_EQUAL_TO_100)){
Log.e("kenyang", "percentage is not equal to 100");
}
}
Now it doesn't give me an error
If I try making it in such a way that the percentage is less than 100, but then it throws an exception. So that means that with this logic, it should work, it does send me 2 logs, but thats it:
10-08 16:10:11.556 12591-12591/nl.hgrams.passenger I/net.kenyang.piechart.PieChartīš• PieChart init
10-08 16:10:11.626 12591-12591/nl.hgrams.passenger I/net.kenyang.piechart.PieChartīš• onDraw

Did it like this and it worked then:
final PieRenderer pieRenderer = pieChart.getRenderer(PieRenderer.class);
pieRenderer.setDonutSize((float) 75 / 100, PieRenderer.DonutMode.PERCENT);
selectDataType();
pieChart.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(pieRenderer.getContainingSegment(new PointF(event.getX(), event.getY())) == bikeS){
segment = 0;
selectSegment(segment, true);
}
if(pieRenderer.getContainingSegment(new PointF(event.getX(), event.getY())) == carS){
segment = 1;
selectSegment(segment, true);
}
if(pieRenderer.getContainingSegment(new PointF(event.getX(), event.getY())) == transitS){
segment = 2;
selectSegment(segment, true);
}
if(pieRenderer.getContainingSegment(new PointF(event.getX(), event.getY())) == walkS){
segment = 3;
selectSegment(segment, true);
}
return false;
}
});
pieChart.removeSegment(carS);
pieChart.removeSegment(walkS);
pieChart.removeSegment(transitS);
pieChart.removeSegment(bikeS);
bikeS = new Segment("", tm.getBicycling());
carS = new Segment("", tm.getDriving());
transitS = new Segment("", tm.getTransit());
walkS = new Segment("", tm.getWalking());
pieChart.addSeries(bikeS, new SegmentFormatter(bikeCP, bikeCP, bikeCP, bikeCP));
pieChart.addSeries(carS, new SegmentFormatter(carC, carC, carC, carC));
pieChart.addSeries(transitS, new SegmentFormatter(transitC, transitC, transitC, transitC));
pieChart.addSeries(walkS, new SegmentFormatter(walkC, walkC, walkC, walkC));
typeText.setText(getString(R.string.bike));
typePercent.setTextColor(getResources().getColor(R.color.bike_color));
typeImage.setImageResource(R.drawable.profile_travel_mode_pie_bicycling);
pieChart.invalidate();

Related

Android SimpleGraph issues with labeling and automatic x-axis scroll

I am working on an Android app and I have a graph of sensor readings: temp/humidity/wind plotted on Y axis, and then time/date on the X-axis. I am using the SimpleGraph library. For the most part everything works great. However, there are a 2-3 issues I've gotten stuck on.
If I specify a number for labels, such as 3 for my main screen, It won't scroll to the end, or which would be preferably, it doesn't just show 3 labels and all the data for the time specified. Instead it shows me the first three labels and cuts the data. If I try graph.getViewport().scrollToEnd(); nothing changes.
On my 'FullGraphActivity' I am still missing the last couple of hours of data...sometimes. Othertimes, it will show.
So I know I am getting the correct data points because my logs show them. I am pretty sure they are being plotted out of view. What I'd really like is to figure out how to get the data and labels to correctly plot based on my time selection. Such as day / week / month. I've included the two main classes, and an example call for the 3 labeled call.
I'm probably missing something simple. Appreciate any suggestions, comments.
Thanks!
Call from main screen with label count specified:
graphTemp = (GraphView) findViewById(R.id.graphTemp);
try {
GraphUtility gu = new GraphUtility(1,1,3,true,false, this,celsius);
gu.grapher( this,graphTemp, gu.seriesBuilder(
gu.getTempData(gu.getSixHours())));
This is where I am setting up the simple graph:
public class GraphUtility {
public int focus;
public Activity activity;
public MainActivity mainActivity;
public Context context;
Constants constants;
private final static int graphColor
Color.parseColor("#6a0c05");
private double maxYBound = 0;
private double minYBound = 999;
private int time = 0;
private int labelCount = 0;
private boolean maxy = true;
private boolean miny = true;
private boolean celsius;
public GraphUtility(int focus, int time, int labelCount,boolean maxy, boolean miny, MainActivity mainActivity, boolean celsius) {
this.focus = focus;
this.time = time;
this.labelCount = labelCount;
context = mainActivity;
this.mainActivity = mainActivity;
this.miny = miny;
this.maxy = maxy;
this.celsius = celsius;
}
public void grapher(Context context, GraphView graph, LineGraphSeries[] seriesArray){
try{
graph.removeAllSeries();
LineGraphSeries series = new LineGraphSeries();
series.clearReference(graph);
if(focus==0){
for(int i = 0; i<seriesArray.length; i++){
// series = new LineGraphSeries();
series = seriesArray[i];
series.setDrawBackground(true);
if(i == 0) {
series.setColor(Color.parseColor("#8d1007"));
series.setBackgroundColor(Color.parseColor("#8d1007"));
}
if(i == 1) {
series.setColor(Color.parseColor("#551a8b"));
series.setBackgroundColor(Color.parseColor("#551a8b"));
}
if(i == 2) {
series.setColor(Color.parseColor("#FF0008F0"));
series.setBackgroundColor(Color.parseColor("#FF0008F0"));
}
series.setDataPointsRadius(2);
series.setThickness(2);
graph.addSeries(series);
}
}
if(focus == 1){
series = seriesArray[0];
series.setDrawBackground(true);
series.setColor(Color.parseColor("#8d1007"));
series.setBackgroundColor(Color.parseColor("#8d1007"));
}
if(focus == 2){
series = seriesArray[1];
series.setDrawBackground(true);
series.setColor(Color.parseColor("#8d1007"));
series.setBackgroundColor(Color.parseColor("#8d1007"));
}
if(focus == 3){
series = seriesArray[2];
series.setDrawBackground(true);
series.setColor(Color.parseColor("#8d1007"));
series.setBackgroundColor(Color.parseColor("#8d1007"));
}
series.setDataPointsRadius(2);
series.setThickness(2);
graph.addSeries(series);
//graph.addSeries(series);
graph.getGridLabelRenderer().setGridColor(graphColor);
graph.getGridLabelRenderer().setHorizontalLabelsColor(graphColor);
graph.getGridLabelRenderer().setVerticalLabelsColor(graphColor);
graph.getGridLabelRenderer().setGridStyle(GridLabelRenderer.GridStyle.BOTH);
graph.getViewport().scrollToEnd();
//Add 5 percent for easier readability
if(maxy) {
graph.getViewport().setYAxisBoundsManual(true);
maxYBound = maxYBound + (maxYBound* .05);
maxYBound= 5*(Math.ceil(Math.abs(maxYBound/5)));
if(maxYBound ==0){
maxYBound=1;
}
graph.getViewport().setMaxY(maxYBound);
}
//Minus 5 percent
if(minYBound !=0) {
if(miny) {
graph.getViewport().setYAxisBoundsManual(true);
minYBound = minYBound - (minYBound * .05);
minYBound= 5*(Math.floor(Math.abs(minYBound/5)));
Log.d("BTWeather-minYval", String.valueOf(minYBound));
//TODO Empty sensors causes crash.
graph.getViewport().setMinY(minYBound);
}
}
if(labelCount > 0){
graph.getGridLabelRenderer().setNumHorizontalLabels(labelCount);
}
graph.getGridLabelRenderer().setHumanRounding(true);
// graph.getGridLabelRenderer().setTextSize(35);
graph.getGridLabelRenderer().reloadStyles();
java.text.DateFormat dateTimeFormatter = DateFormat.getTimeFormat(context);
if(time==1) {
graph.getGridLabelRenderer().setLabelFormatter(
new DateAsXAxisLabelFormatter(graph.getContext(),
dateTimeFormatter));
}else{
graph.getGridLabelRenderer().setLabelFormatter(
new DateAsXAxisLabelFormatter(graph.getContext()));
}
//
}catch(Exception e){
Log.d("BTWeather-error21", e.toString());
}
}
// TODO Graphs not advancing again showing hours behind instead of latest sensor
public LineGraphSeries[] seriesBuilder(List<Sensors> sensorsList){
LineGraphSeries[] seriesArray = new LineGraphSeries[3];
try{
DataPoint d = null;
DataPoint[] dataPoints = new DataPoint[sensorsList.size()];
DataPoint[] dataPointsH = new DataPoint[sensorsList.size()];
DataPoint[] dataPointsW = new DataPoint[sensorsList.size()];
Date date1 = new Date();
int i = 0;
Log.d("BTWeather-seriesbuilder",
" Length of sensorlist: " + String.valueOf(sensorsList.size()));
if(sensorsList.size()==0){
minYBound = 0;
}
try{
for(Sensors sensor: sensorsList){
findMaxY(sensor);
findMinY(sensor);
try {
date1 = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss").parse(sensor.getmDate());
//Log.d("BTWeather-sensorlistFG",
// String.valueOf(date1)+" - " + String.valueOf(sensor.getmTemp()) );
} catch (ParseException e) {
e.printStackTrace();
}
if( isCelsius()){
d = new DataPoint(date1, Double.valueOf(sensor.getmTemp()));
}else{
double tmp = mainActivity.cToF(Double.valueOf(sensor.getmTemp()));
// Log.d("BTWeather-seriesdump",String.valueOf(tmp));
d = new DataPoint(date1, tmp);
}
dataPoints[i]= d;
d = new DataPoint(date1, Double.valueOf(sensor.getmHumidity()));
dataPointsH[i]=d;
d = new DataPoint(date1, Double.valueOf(sensor.getmWind()));
dataPointsW[i]=d;
i++;
}
seriesArray[0] = new LineGraphSeries<>(dataPoints);
seriesArray[1] = new LineGraphSeries<>(dataPointsH);
seriesArray[2] = new LineGraphSeries<>(dataPointsW);
}catch(Exception e){
Log.d("BTWeather-error20", e.toString());
}
}catch (Exception e){
Log.d("BTWeather-error22", e.toString());
}
return seriesArray;
}
//TODO min / max not resetting propperly for days/weeks etc
public void findMaxY (Sensors sensor){
try{
//Focus passed from main activity on graph click
if(focus ==1){
if( isCelsius()) {
if (Double.valueOf(sensor.getmTemp()) > maxYBound) {
maxYBound = Double.valueOf(sensor.getmTemp());
}
}else if(mainActivity.cToF(Double.valueOf(sensor.getmTemp()))>maxYBound){
maxYBound=mainActivity.cToF(Double.valueOf(sensor.getmTemp()));
}
}
else if(focus == 2){
if( Double.valueOf(sensor.getmHumidity())> maxYBound){
maxYBound = Double.valueOf(sensor.getmHumidity());
}
}
else if(focus == 3){
if(Double.valueOf(sensor.getmWind())> maxYBound){
maxYBound = Double.valueOf(sensor.getmWind());
}
}}
catch (Exception e){
Log.d("BTWeather-error19", e.toString());
}
}
public void findMinY (Sensors sensor){
if(sensor != null) {
try {
//Focus passed from main activity on graph click
if (focus == 1) {
if (isCelsius()) {
if (Double.valueOf(sensor.getmTemp()) < minYBound) {
minYBound = Double.valueOf(sensor.getmTemp());
}
} else if (mainActivity.cToF(Double.valueOf(sensor.getmTemp())) < minYBound) {
minYBound = mainActivity.cToF(Double.valueOf(sensor.getmTemp()));
}
} else if (focus == 2) {
if (Double.valueOf(sensor.getmHumidity()) < minYBound) {
minYBound = Double.valueOf(sensor.getmHumidity());
}
} else if (focus == 3) {
if (Double.valueOf(sensor.getmWind()) < minYBound) {
minYBound = Double.valueOf(sensor.getmWind());
}
}
} catch (Exception e) {
Log.d("BTWeather-error18", e.toString());
}
}else{
minYBound=0;
}
}
//Database
public static String getYesterday(){
//return new Date(System.currentTimeMillis()-24*60*60*1000);
long day = TimeUnit.DAYS.toMillis(1);
String start= DateFormat.format("MM-dd-yyyy HH:mm:ss",
new Date(System.currentTimeMillis() - day)).toString();
return start;
}
public static String getSixHours(){
//return new Date(System.currentTimeMillis()-24*60*60*1000);
long day = TimeUnit.HOURS.toMillis(6);
String start= DateFormat.format("MM-dd-yyyy HH:mm:ss",
new Date(System.currentTimeMillis() - day)).toString();
return start;
}
public static String getWeek(){
//return new Date(System.currentTimeMillis()-24*60*60*1000);
long week = TimeUnit.DAYS.toMillis(7);
String start= DateFormat.format("MM-dd-yyyy HH:mm:ss",
new Date(System.currentTimeMillis() - week)).toString();
return start;
}
public static String getMonth(){
//return new Date(System.currentTimeMillis()-24*60*60*1000);
long month = TimeUnit.DAYS.toMillis(30);
String start= DateFormat.format("MM-dd-yyyy HH:mm:ss",
new Date(System.currentTimeMillis() - month)).toString();
return start;
}
public static Date getMeTomorrow(){
return new Date(System.currentTimeMillis());
}
public List<Sensors> getTempData(String start){
SensorsDatabase sDb = SensorsDatabase.getSensorsDatabase(context);
List<Sensors> dataPoints = null;
Date date1 = new Date();
try {
dataPoints = sDb.sensorsDao().findTempByDate(
start,
DateFormat.format("MM-dd-yyyy HH:mm:ss", getMeTomorrow()).toString());
} catch (Exception e) {
Log.d("BTWeather-error8", String.valueOf(e));
}
return dataPoints;
}
public boolean isCelsius() {
return celsius;
}
}
This activity is for full view of the graph. Here it's mostly working. However, as said above, sometimes the last couple of hours worth of data is being cut off. Say its 2:30, I'll see data & labels up to 12:30
public class FullGraphActivity extends AppCompatActivity {
GraphView graph;
private TextView mTextMessage;
private final static int graphColor = Color.parseColor("#6a0c05");
private MainActivity mainActivity;
private int focus =0;
private int time = 0;
GraphUtility gu;
private boolean celsius;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.graph_hour:
time=1;
if(focus ==1 )
mTextMessage.setText(R.string.graph_hour_temp);
if(focus ==2 )
mTextMessage.setText(R.string.graph_hour_humid);
if(focus ==3 )
mTextMessage.setText(R.string.graph_hour_wind);
try{
gu = new GraphUtility(focus,time,0,true,true,mainActivity,celsius);
gu.grapher(getApplicationContext(),graph,gu.seriesBuilder(gu.getTempData(gu.getYesterday())));
}catch(Exception e){
Log.d("BTWeather-error15", e.toString());
}
return true;
case R.id.graph_day:
time=2;
if(focus ==1 )
mTextMessage.setText(R.string.graph_day_temp);
if(focus ==2 )
mTextMessage.setText(R.string.graph_day_humid);
if(focus ==3 )
mTextMessage.setText(R.string.graph_day_wind);
try{
gu = new GraphUtility(focus,time,0,true,true,mainActivity,celsius );
gu.grapher(getApplicationContext(),graph,gu.seriesBuilder(gu.getTempData(gu.getWeek())));
}catch(Exception e){
Log.d("BTWeather-error15", e.toString());
}
return true;
case R.id.graph_week:
time=3;
if(focus ==1 )
mTextMessage.setText(R.string.graph_week_temp);
if(focus ==2 )
mTextMessage.setText(R.string.graph_week_humid);
if(focus ==3 )
mTextMessage.setText(R.string.graph_week_wind);
try{
gu = new GraphUtility(focus,time,0,true,true,mainActivity,celsius );
gu.grapher(getApplicationContext(),graph,gu.seriesBuilder(gu.getTempData(gu.getMonth())));
}catch(Exception e){
Log.d("BTWeather-error15", e.toString());
}
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_graph);
Intent mIntent = getIntent();
focus = mIntent.getIntExtra("focus", 0);
celsius = mIntent.getBooleanExtra("celsius", false);
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.graphMenu);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
mainActivity = new MainActivity() ;
graph = (GraphView) findViewById(R.id.fullGraph);
// Setting the very 1st item as home screen.
navigation.setSelectedItemId(R.id.graph_hour);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home){
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Hopefully this isn't too much info. Again, any comments greatly appreciated. Full code repo if it helps.
Ok, so as usual, after deciding to post I was able to work out a solution with the help of the examples on simplegraphs doc. I thought I mirrored the date example from the doc but I had left out a key section:
// set manual x bounds to have nice steps
graph.getViewport().setMinX(start);
graph.getViewport().setMaxX(System.currentTimeMillis());
graph.getViewport().setXAxisBoundsManual(true);
For some reason I wasn't able to clear each graphs style/data correctly despite using the clear/resets provided in the API. Rather than waste too much time on it I decided to create three graphviews in my layout then hide the ones not in use. This isn't the best method, but it seems to not impact performance. See below for the code changes. Note some changes are made for style reasons.
I changed my grapher method to include the double start which is the time to start from:
Class GraphUtility
public void grapher(Context context, GraphView graph, LineGraphSeries[] seriesArray, Double start){
try{
graph.removeAllSeries();
graph.getGridLabelRenderer().resetStyles();
LineGraphSeries series = new LineGraphSeries();
series.clearReference(graph);
if(focus==0) {
for (int i = 0; i < seriesArray.length; i++) {
// series = new LineGraphSeries();
series = seriesArray[i];
series.setDrawBackground(true);
if (i == 0) {
series.setColor(Color.parseColor("#8d1007"));
series.setBackgroundColor(Color.parseColor("#4D6a0c05"));
}
if (i == 1) {
series.setColor(Color.parseColor("#00004C"));
series.setBackgroundColor(Color.parseColor("#4D00004C"));
}
if (i == 2) {
series.setColor(Color.parseColor("#006600"));
series.setBackgroundColor(Color.parseColor("#4D006600"));
}
series.setDataPointsRadius(4);
series.setThickness(4);
graph.getGridLabelRenderer().setGridColor(graphColor);
graph.getGridLabelRenderer().setHorizontalLabelsColor(graphColor);
graph.getGridLabelRenderer().setVerticalLabelsColor(graphColor);
graph.addSeries(series);
}
}
if(focus == 1){
series = seriesArray[0];
series.setDrawBackground(true);
series.setColor(Color.parseColor("#8d1007"));
series.setBackgroundColor(Color.parseColor("#4D6a0c05"));
graph.getGridLabelRenderer().setGridColor(Color.parseColor("#8d1007"));
graph.getGridLabelRenderer().setHorizontalLabelsColor(Color.parseColor("#8d1007"));
graph.getGridLabelRenderer().setVerticalLabelsColor(Color.parseColor("#8d1007"));
series.setDataPointsRadius(2);
series.setThickness(2);
graph.addSeries(series);
}
if(focus == 2){
series = seriesArray[1];
series.setDrawBackground(true);
series.setColor(Color.parseColor("#00004C"));
series.setBackgroundColor(Color.parseColor("#4D00004C"));
graph.getGridLabelRenderer().setGridColor(Color.parseColor("#00004C"));
graph.getGridLabelRenderer().setHorizontalLabelsColor(Color.parseColor("#00004C"));
graph.getGridLabelRenderer().setVerticalLabelsColor(Color.parseColor("#00004C"));
series.setDataPointsRadius(2);
series.setThickness(2);
graph.addSeries(series);
}
if(focus == 3){
series = seriesArray[2];
series.setDrawBackground(true);
series.setColor(Color.parseColor("#006600"));
series.setBackgroundColor(Color.parseColor("#4D006600"));
graph.getGridLabelRenderer().setGridColor(Color.parseColor("#006600"));
graph.getGridLabelRenderer().setHorizontalLabelsColor(Color.parseColor("#006600"));
graph.getGridLabelRenderer().setVerticalLabelsColor(Color.parseColor("#006600"));
series.setDataPointsRadius(2);
series.setThickness(2);
graph.addSeries(series);
}
graph.getGridLabelRenderer().setGridStyle(GridLabelRenderer.GridStyle.BOTH);
//Add 5 percent for easier readability
Log.d(Constants.LOG_TAG,"MaxY" + String.valueOf(maxYBound));
if(maxy) {
graph.getViewport().setYAxisBoundsManual(true);
maxYBound = maxYBound + (maxYBound* .05);
maxYBound= 5*(Math.ceil(Math.abs(maxYBound/5)));
if(maxYBound ==0){
maxYBound=1;
}
graph.getViewport().setMaxY(maxYBound);
}
//Minus 5 percent
Log.d(Constants.LOG_TAG,"MinY" + String.valueOf(minYBound));
if(minYBound !=0) {
if(miny) {
graph.getViewport().setYAxisBoundsManual(true);
minYBound = minYBound - (minYBound * .05);
minYBound= 5*(Math.floor(Math.abs(minYBound/5)));
Log.d("BTWeather-minYval", String.valueOf(minYBound));
graph.getViewport().setMinY(minYBound);
}
}else{
graph.getViewport().setMinY(minYBound);
}
if(labelCount > 0){
graph.getGridLabelRenderer().setNumHorizontalLabels(labelCount);
}
if(time==1) {
java.text.DateFormat dateTimeFormatter = DateFormat.getTimeFormat(context);
graph.getGridLabelRenderer().setLabelFormatter(
new DateAsXAxisLabelFormatter(graph.getContext(),
dateTimeFormatter));
}else{
graph.getGridLabelRenderer().setLabelFormatter(new DateAsXAxisLabelFormatter(context));
}
//graph.getGridLabelRenderer().setNumHorizontalLabels(labelCount); // only 4 because of the space
// set manual x bounds to have nice steps
graph.getViewport().setMinX(start);
graph.getViewport().setMaxX(System.currentTimeMillis());
graph.getViewport().setXAxisBoundsManual(true);
// as we use dates as labels, the human rounding to nice readable numbers
// is not necessary
graph.getGridLabelRenderer().setHumanRounding(false);
//graph.getGridLabelRenderer().reloadStyles();
}catch(Exception e){
Log.d("BTWeather-error21", e.toString());
}
}
Class FullGraphActivity: Only changes needed were for the grapher call and for hiding/showing the correct view depending on the time call.
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.graph_hour:
time=1;
if(focus==0) {
getSupportActionBar().setTitle(R.string.AllHourly);
try {
GraphView graph2;
graph2 = (GraphView) findViewById(R.id.fullGraph2);
graph2.setVisibility(View.INVISIBLE);
graph2 = (GraphView) findViewById(R.id.fullGraph3);
graph2.setVisibility(View.INVISIBLE);
GraphView graph;
graph = (GraphView) findViewById(R.id.fullGraph);
graph.setVisibility(View.VISIBLE);
gu = new GraphUtility(focus, time, 6, true, true, mainActivity, celsius);
gu.grapher(getApplicationContext(), graph, gu.seriesBuilder(gu.getTempData(gu.getYesterday())),gu.getYesterdayDouble());
} catch (Exception e) {
Log.d("BTWeather-error15", e.toString());
}
}else {
if (focus == 1)
getSupportActionBar().setTitle(R.string.graph_hour_temp);
if (focus == 2)
getSupportActionBar().setTitle(R.string.graph_hour_humid);
if (focus == 3)
getSupportActionBar().setTitle(R.string.graph_hour_wind);
try {
GraphView graph2;
graph2 = (GraphView) findViewById(R.id.fullGraph2);
graph2.setVisibility(View.INVISIBLE);
graph2 = (GraphView) findViewById(R.id.fullGraph3);
graph2.setVisibility(View.INVISIBLE);
GraphView graph;
graph = (GraphView) findViewById(R.id.fullGraph);
graph.setVisibility(View.VISIBLE);
graph.getGridLabelRenderer().resetStyles();
graph.removeAllSeries();
gu = new GraphUtility(focus, time, 6, true, true, mainActivity, celsius);
gu.grapher(getApplicationContext(), graph, gu.seriesBuilder(gu.getTempData(gu.getYesterday())),gu.getYesterdayDouble());
} catch (Exception e) {
Log.d("BTWeather-error15", e.toString());
}
}
return true;
case R.id.graph_day:
time=2;
if(focus==0){
getSupportActionBar().setTitle(R.string.AllDaily);
try {
GraphView graph2;
graph2 = (GraphView) findViewById(R.id.fullGraph);
graph2.setVisibility(View.INVISIBLE);
graph2 = (GraphView) findViewById(R.id.fullGraph3);
graph2.setVisibility(View.INVISIBLE);
GraphView graph;
graph = (GraphView) findViewById(R.id.fullGraph2);
graph.setVisibility(View.VISIBLE);
graph.getGridLabelRenderer().resetStyles();
graph.removeAllSeries();
gu = new GraphUtility(focus, time, 7, true, true, mainActivity, celsius);
gu.grapher(getApplicationContext(), graph, gu.seriesBuilder(gu.getTempData(gu.getWeek())),gu.getWeekDouble());
} catch (Exception e) {
Log.d("BTWeather-error15", e.toString());
}
}else {
if (focus == 1)
getSupportActionBar().setTitle(R.string.graph_day_temp);
if (focus == 2)
getSupportActionBar().setTitle(R.string.graph_day_humid);
if (focus == 3)
getSupportActionBar().setTitle(R.string.graph_day_wind);
try {
GraphView graph2;
graph2 = (GraphView) findViewById(R.id.fullGraph);
graph2.setVisibility(View.INVISIBLE);
graph2 = (GraphView) findViewById(R.id.fullGraph3);
graph2.setVisibility(View.INVISIBLE);
GraphView graph;
graph = (GraphView) findViewById(R.id.fullGraph2);
graph.setVisibility(View.VISIBLE);
graph.getGridLabelRenderer().resetStyles();
graph.removeAllSeries();
gu = new GraphUtility(focus, time, 7, true, true, mainActivity, celsius);
gu.grapher(getApplicationContext(), graph, gu.seriesBuilder(gu.getTempData(gu.getWeek())),gu.getWeekDouble());
} catch (Exception e) {
Log.d("BTWeather-error15", e.toString());
}
}
return true;
case R.id.graph_week:
time=3;
if(focus==0){
getSupportActionBar().setTitle(R.string.AllWeekly);
try {
GraphView graph2;
graph2 = (GraphView) findViewById(R.id.fullGraph);
graph2.setVisibility(View.INVISIBLE);
graph2 = (GraphView) findViewById(R.id.fullGraph2);
graph2.setVisibility(View.INVISIBLE);
GraphView graph;
graph = (GraphView) findViewById(R.id.fullGraph3);
graph.setVisibility(View.VISIBLE);
graph.getGridLabelRenderer().resetStyles();
graph.removeAllSeries();
gu = new GraphUtility(focus, time, 8, false, false, mainActivity, celsius);
gu.grapher(getApplicationContext(), graph, gu.seriesBuilder(gu.getTempData(gu.getMonth())),gu.getMonthDouble());
} catch (Exception e) {
Log.d("BTWeather-error15", e.toString());
}
}else {
if (focus == 1)
getSupportActionBar().setTitle(R.string.graph_week_temp);
if (focus == 2)
getSupportActionBar().setTitle(R.string.graph_week_humid);
if (focus == 3)
getSupportActionBar().setTitle(R.string.graph_week_wind);
try {
GraphView graph2;
graph2 = (GraphView) findViewById(R.id.fullGraph);
graph2.setVisibility(View.INVISIBLE);
graph2 = (GraphView) findViewById(R.id.fullGraph2);
graph2.setVisibility(View.INVISIBLE);
GraphView graph;
graph = (GraphView) findViewById(R.id.fullGraph3);
graph.getGridLabelRenderer().resetStyles();
graph.removeAllSeries();
graph.setVisibility(View.VISIBLE);
gu = new GraphUtility(focus, time, 8, true, true, mainActivity, celsius);
gu.grapher(getApplicationContext(), graph, gu.seriesBuilder(gu.getTempData(gu.getMonth())),gu.getMonthDouble());
} catch (Exception e) {
Log.d("BTWeather-error15", e.toString());
}
}
return true;
}
return false;
}
};
If I find a solution to the multiple views I'll edit this post in case it's useful for someone in the future.
Best,
James

How can I save my current imageview when onClick?

How can I save my current ImageView when I press onClick?
Im currently having the problem that the image that is next in line is being saved instead of the current actual image..
My Code for saving onLike
public class MainActivity extends Activity implements SwipeView.OnCardSwipedListener {
// Declaring variables
private final static int CARDS_MAX_ELEMENTS = 5;
private FrameLayout contentLayout;
private SwipeView mSwipeView;
private View addCardc41;
private Firebase mRef;
public ImageView imageLogo;
public ImageView imageview;
private static final String TAG = "MyActivity";
// Creating array of meals, getting them from the drawable folder
private int[] meals = {
R.drawable.a,
R.drawable.b,
R.drawable.c,
R.drawable.d,
R.drawable.e,
R.drawable.f,
R.drawable.g,
R.drawable.h,
R.drawable.i,
R.drawable.j
};
// Declaring a counter for the next method
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_view_demo);
contentLayout = (FrameLayout) findViewById(R.id.contentLayout);
imageLogo = (ImageView) findViewById(R.id.imageView3);
imageview = (ImageView) findViewById(R.id.imageView);
// Add the swipe view
mSwipeView = new SwipeView(this, R.id.imgSwipeLike, R.id.imgSwipeNope,
this);
contentLayout.addView(mSwipeView);
// Adding the cards initially with the maximum limits of cards.
for (int i = 0; i < CARDS_MAX_ELEMENTS; i++) {
addCard(i);
}
}
/**
* On clicked view.
*
* #param clickedView
* the clicked view
*/
public void onClickedView(View clickedView) {
switch (clickedView.getId()) {
case R.id.imgDisLike: {
mSwipeView.dislikeCard();
break;
}
case R.id.imgLike: {
mSwipeView.likeCard();
break;
}
}
}
#Override
public void onLikes() {
imageview.setDrawingCacheEnabled(true); //Add this line.
imageview.buildDrawingCache();
Bitmap bm=imageview.getDrawingCache();
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
MediaScannerConnection.scanFile(this, new String[] { sdImageMainDirectory.getAbsolutePath() }, null, null);
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e){}
System.out.println("An Card removed");
// Add a card if you needed after any previous card swiped
addCard(0);
}
#Override
public void onDisLikes() {
System.out.println("An Card removed");
// Add a card if you needed after any previous card swiped
addCard(0);
}
#Override
public void onSingleTap() {
}
/**
* Adds the card to the swipe.
*/
private void addCard(int position) {
final View cardView = LayoutInflater.from(this).inflate(
R.layout.item_swipe_view, null);
final ImageView imgMeal = (ImageView) cardView
.findViewById(R.id.imgMeals);
imgMeal.setImageResource(meals[count]);
count++;
if (count == meals.length) {
count = 0;
}
// Add a card to the swipe view..
mSwipeView.addCard(cardView, position);
// Create OnClickListener for the CookBookActivity
// Declare Button for the Cookbook
Button btn = (Button) findViewById(R.id.button3);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, CookbookActivity.class));
}
});
// Check Authentication
mRef = new Firebase(Constants.FIREBASE_URL);
if (mRef.getAuth() == null) {
loadLoginView();
}
}
private void loadLoginView() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
The Library that i'm using for the swiping
//
// credits to IntelliJ IDEA
// (powered by Fernflower decompiler)
package com.rk.lib.view;
import android.content.Context;
import android.os.Handler;
import android.os.Build.VERSION;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnTouchListener;
import android.view.animation.AlphaAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.FrameLayout.LayoutParams;
public class SwipeView extends FrameLayout {
private View mFocusedView;
private View mFocusedViewLike;
private View mFocusedViewNope;
private int mFocusedViewWidth;
private float mPreviousAlpha = 0.0F;
private Integer mLikeResource = Integer.valueOf(0);
private Integer mNopeResource = Integer.valueOf(0);
private static final int MAX_ELEMENTS = 3;
private static final long DELAY_SCROLL_RUNNABLE = 1L;
private static final int SCROLL_LENGTH = 5;
private int mScrolledPixelsX;
private int mScrolledPixelsY;
private int mNeedToScrollX;
private int mNeedToScrollY;
private int mTotalScrolledX;
private int mTotalScrolledY;
private int mScrollLengthX = 5;
private int mScrollLengthY = 5;
private boolean enableTouchSwipe = true;
private Context mContext;
private SwipeView.ScrollMode mScrollModeX;
private SwipeView.ScrollMode mScrollModeY;
private SwipeView.ScrollDirection mScrollDirection;
private int[] paddingX;
private int[] paddingYTop;
private int[] paddingYBottom;
private SwipeView.OnCardSwipedListener mOnCardSwipedListener;
private Handler mScrollHandler;
private Runnable mScrollRunnable;
private final SimpleOnGestureListener simpleOnGestureListener;
public SwipeView(Context context, Integer likeResource, Integer nopeResource, SwipeView.OnCardSwipedListener cardSwipeListener) {
super(context);
this.mScrollModeX = SwipeView.ScrollMode.NONE;
this.mScrollModeY = SwipeView.ScrollMode.NONE;
this.mScrollDirection = SwipeView.ScrollDirection.NONE;
this.paddingX = new int[]{0, 10, 20};
this.paddingYTop = new int[]{0, 10, 20};
this.paddingYBottom = new int[]{20, 10, 0};
this.mScrollHandler = new Handler();
this.mScrollRunnable = new Runnable() {
public void run() {
boolean scrollX;
boolean scrollY;
int scrollX1;
int scrollY1;
if(SwipeView.this.mScrollDirection == SwipeView.ScrollDirection.OUT) {
if(SwipeView.this.mNeedToScrollX <= 0 && SwipeView.this.mNeedToScrollY <= 0) {
SwipeView.this.mScrollHandler.removeCallbacks(SwipeView.this.mScrollRunnable);
SwipeView.this.removeView(SwipeView.this.mFocusedView);
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
SwipeView.this.mOnCardSwipedListener.onLikes();
} else if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.RIGHT) {
SwipeView.this.mOnCardSwipedListener.onDisLikes();
}
SwipeView.this.alignCardsPadding();
} else {
if(SwipeView.this.mNeedToScrollX < SwipeView.this.mScrollLengthX) {
SwipeView.this.mScrollLengthX = SwipeView.this.mNeedToScrollX;
SwipeView.this.mNeedToScrollX = 0;
} else {
SwipeView.this.mNeedToScrollX = SwipeView.this.mNeedToScrollX - SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mNeedToScrollY < SwipeView.this.mScrollLengthY) {
SwipeView.this.mScrollLengthY = SwipeView.this.mNeedToScrollY;
SwipeView.this.mNeedToScrollY = 0;
} else {
SwipeView.this.mNeedToScrollY = SwipeView.this.mNeedToScrollY - SwipeView.this.mScrollLengthY;
}
scrollX = false;
scrollY = false;
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
scrollX1 = -SwipeView.this.mScrollLengthX;
} else {
scrollX1 = SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mScrollModeY == SwipeView.ScrollMode.TOP) {
scrollY1 = -SwipeView.this.mScrollLengthY;
} else {
scrollY1 = SwipeView.this.mScrollLengthY;
}
SwipeView.this.mFocusedView.scrollBy(scrollX1, scrollY1);
SwipeView.this.mScrollHandler.postDelayed(SwipeView.this.mScrollRunnable, 1L);
}
} else if(SwipeView.this.mScrollDirection == SwipeView.ScrollDirection.IN) {
if(SwipeView.this.mTotalScrolledX <= 0 && SwipeView.this.mTotalScrolledY <= 0) {
SwipeView.this.mScrollHandler.removeCallbacks(SwipeView.this.mScrollRunnable);
SwipeView.this.mScrollDirection = SwipeView.ScrollDirection.NONE;
} else {
if(SwipeView.this.mTotalScrolledX < SwipeView.this.mScrollLengthX) {
SwipeView.this.mScrollLengthX = SwipeView.this.mTotalScrolledX;
SwipeView.this.mTotalScrolledX = 0;
} else {
SwipeView.this.mTotalScrolledX = SwipeView.this.mTotalScrolledX - SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mTotalScrolledY < SwipeView.this.mScrollLengthY) {
SwipeView.this.mScrollLengthY = SwipeView.this.mTotalScrolledY;
SwipeView.this.mTotalScrolledY = 0;
} else {
SwipeView.this.mTotalScrolledY = SwipeView.this.mTotalScrolledY - SwipeView.this.mScrollLengthY;
}
scrollX = false;
scrollY = false;
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
scrollX1 = SwipeView.this.mScrollLengthX;
} else {
scrollX1 = -SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mScrollModeY == SwipeView.ScrollMode.TOP) {
scrollY1 = -SwipeView.this.mScrollLengthY;
} else {
scrollY1 = SwipeView.this.mScrollLengthY;
}
SwipeView.this.mFocusedView.scrollBy(scrollX1, scrollY1);
SwipeView.this.mScrollHandler.postDelayed(SwipeView.this.mScrollRunnable, 1L);
}
}
}
};
this.simpleOnGestureListener = new SimpleOnGestureListener() {
public boolean onSingleTapConfirmed(MotionEvent e) {
SwipeView.this.mOnCardSwipedListener.onSingleTap();
return super.onSingleTapConfirmed(e);
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if(SwipeView.this.mFocusedView != null) {
SwipeView.this.mScrolledPixelsX = SwipeView.this.mScrolledPixelsX + (int)distanceX;
SwipeView.this.mScrolledPixelsY = SwipeView.this.mScrolledPixelsY + (int)distanceY;
SwipeView.this.mFocusedView.scrollBy((int)distanceX, (int)distanceY);
float alpha = (float)SwipeView.this.mScrolledPixelsX / (float)SwipeView.this.mFocusedViewWidth;
if(alpha > 0.0F) {
SwipeView.this.mFocusedViewNope.setVisibility(0);
SwipeView.this.mFocusedViewLike.setVisibility(8);
SwipeView.setAlpha(SwipeView.this.mFocusedViewNope, SwipeView.this.mPreviousAlpha, alpha);
SwipeView.this.mPreviousAlpha = alpha;
} else {
SwipeView.this.mFocusedViewNope.setVisibility(8);
SwipeView.this.mFocusedViewLike.setVisibility(0);
SwipeView.setAlpha(SwipeView.this.mFocusedViewLike, SwipeView.this.mPreviousAlpha, -alpha);
SwipeView.this.mPreviousAlpha = -alpha;
}
}
return true;
}
};
this.mContext = context;
this.mLikeResource = likeResource;
this.mNopeResource = nopeResource;
this.mOnCardSwipedListener = cardSwipeListener;
float density = this.getResources().getDisplayMetrics().density;
for(int gestureDetector = 0; gestureDetector < this.paddingX.length; ++gestureDetector) {
this.paddingX[gestureDetector] = (int)((float)this.paddingX[gestureDetector] * density);
this.paddingYTop[gestureDetector] = (int)((float)this.paddingYTop[gestureDetector] * density);
this.paddingYBottom[gestureDetector] = (int)((float)this.paddingYBottom[gestureDetector] * density);
}
final GestureDetector var7 = new GestureDetector(this.mContext, this.simpleOnGestureListener);
this.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(SwipeView.this.getChildCount() > 0) {
if(SwipeView.this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return false;
} else if(!SwipeView.this.enableTouchSwipe) {
return false;
} else {
var7.onTouchEvent(event);
switch(event.getAction()) {
case 0:
if(SwipeView.this.getChildCount() > 0) {
SwipeView.this.mFocusedView = SwipeView.this.getChildAt(SwipeView.this.getChildCount() - 1);
SwipeView.this.mFocusedViewLike = SwipeView.this.mFocusedView.findViewById(SwipeView.this.mLikeResource.intValue());
SwipeView.this.mFocusedViewNope = SwipeView.this.mFocusedView.findViewById(SwipeView.this.mNopeResource.intValue());
SwipeView.this.mFocusedViewWidth = SwipeView.this.mFocusedView.getWidth();
SwipeView.this.mFocusedView.setPadding(SwipeView.this.paddingX[0], 0, SwipeView.this.paddingX[0], 0);
}
SwipeView.this.resetScrollingValues();
break;
case 1:
SwipeView.this.alignCardsPadding();
if(SwipeView.this.mScrolledPixelsX < 0) {
SwipeView.this.mScrollModeX = SwipeView.ScrollMode.LEFT;
SwipeView.this.mTotalScrolledX = -SwipeView.this.mScrolledPixelsX;
} else {
SwipeView.this.mScrollModeX = SwipeView.ScrollMode.RIGHT;
SwipeView.this.mTotalScrolledX = SwipeView.this.mScrolledPixelsX;
}
if(SwipeView.this.mScrolledPixelsY < 0) {
SwipeView.this.mScrollModeY = SwipeView.ScrollMode.BOTTOM;
SwipeView.this.mTotalScrolledY = -SwipeView.this.mScrolledPixelsY;
} else {
SwipeView.this.mScrollModeY = SwipeView.ScrollMode.TOP;
SwipeView.this.mTotalScrolledY = SwipeView.this.mScrolledPixelsY;
}
SwipeView.this.detectSwipe();
}
return true;
}
} else {
return false;
}
}
});
}
public void addCard(View view, int position) {
if(this.getChildCount() <= 3 && position < 3) {
LinearLayout viewLayout = new LinearLayout(this.mContext);
viewLayout.setLayoutParams(new LayoutParams(-1, -1));
view.setLayoutParams(new LayoutParams(-1, -1));
viewLayout.addView(view);
viewLayout.setPadding(this.paddingX[position], this.paddingYTop[position], this.paddingX[position], this.paddingYBottom[position]);
this.addView(viewLayout, 0);
}
}
public void removeFocusedCard() {
this.removeView(this.mFocusedView);
this.alignCardsPadding();
}
private void alignCardsPadding() {
int i = 0;
for(int j = this.getChildCount() - 1; j >= 0; --j) {
this.getChildAt(j).setPadding(this.paddingX[i], this.paddingYTop[i], this.paddingX[i], this.paddingYBottom[i]);
++i;
}
this.mScrollDirection = SwipeView.ScrollDirection.NONE;
}
private void resetScrollingValues() {
this.mPreviousAlpha = 0.0F;
this.mNeedToScrollX = 0;
this.mScrolledPixelsX = 0;
this.mTotalScrolledX = 0;
this.mNeedToScrollY = 0;
this.mScrolledPixelsY = 0;
this.mTotalScrolledY = 0;
this.mScrollLengthX = 5;
this.mScrollLengthY = 5;
this.mScrollModeX = SwipeView.ScrollMode.NONE;
this.mScrollModeY = SwipeView.ScrollMode.NONE;
}
public void resetFocuedView() {
if(this.getChildCount() > 0) {
View mFocusedView = this.getChildAt(this.getChildCount() - 1);
View mFocusedViewLike = mFocusedView.findViewById(this.mLikeResource.intValue());
View mFocusedViewNope = mFocusedView.findViewById(this.mNopeResource.intValue());
setAlpha(mFocusedViewLike, 0.0F, 0.0F);
setAlpha(mFocusedViewNope, 0.0F, 0.0F);
mFocusedView.scrollTo(0, 0);
}
}
private void detectSwipe() {
int imageHalf = this.mFocusedView.getWidth() / 2;
this.mNeedToScrollX = this.mFocusedView.getWidth() - this.mTotalScrolledX;
if(this.mScrollDirection == SwipeView.ScrollDirection.NONE) {
if(this.mNeedToScrollX < imageHalf) {
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
} else {
this.mScrollDirection = SwipeView.ScrollDirection.IN;
setAlpha(this.mFocusedViewLike, 0.0F, 0.0F);
setAlpha(this.mFocusedViewNope, 0.0F, 0.0F);
}
}
this.mScrollHandler.post(this.mScrollRunnable);
}
public void likeCard() {
if(this.getChildCount() > 0) {
this.mFocusedView = this.getChildAt(this.getChildCount() - 1);
this.mFocusedViewLike = this.mFocusedView.findViewById(this.mLikeResource.intValue());
this.mFocusedViewNope = this.mFocusedView.findViewById(this.mNopeResource.intValue());
if(this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return;
}
this.resetScrollingValues();
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
this.mScrollModeX = SwipeView.ScrollMode.LEFT;
this.mFocusedViewLike.setVisibility(0);
setAlpha(this.mFocusedViewLike, 0.0F, 1.0F);
this.detectSwipe();
}
}
public void dislikeCard() {
if(this.getChildCount() > 0) {
this.mFocusedView = this.getChildAt(this.getChildCount() - 1);
this.mFocusedViewLike = this.mFocusedView.findViewById(this.mLikeResource.intValue());
this.mFocusedViewNope = this.mFocusedView.findViewById(this.mNopeResource.intValue());
if(this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return;
}
this.resetScrollingValues();
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
this.mScrollModeX = SwipeView.ScrollMode.RIGHT;
this.mFocusedViewNope.setVisibility(0);
setAlpha(this.mFocusedViewNope, 0.0F, 1.0F);
this.detectSwipe();
}
}
public void setTouchable(boolean touchable) {
this.enableTouchSwipe = touchable;
}
public static void setAlpha(View view, float fromAlpha, float toAlpha) {
if(VERSION.SDK_INT < 11) {
AlphaAnimation alphaAnimation = new AlphaAnimation(fromAlpha, toAlpha);
alphaAnimation.setDuration(0L);
alphaAnimation.setFillAfter(true);
view.startAnimation(alphaAnimation);
} else {
view.setAlpha(toAlpha);
}
}
public interface OnCardSwipedListener {
void onLikes();
void onDisLikes();
void onSingleTap();
}
private static enum ScrollDirection {
IN,
OUT,
NONE;
private ScrollDirection() {
}
}
private static enum ScrollMode {
LEFT,
RIGHT,
TOP,
BOTTOM,
NONE;
private ScrollMode() {
}
}
}
ATTEMPT #3
This is the code that i've tried but I keep getting the same result (read comment below what I have done:
FrameLayout view = (FrameLayout)findViewById(R.id.contentLayout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
I believe the image you are trying to save is getting removed during the onSwipe due to the library code. I think you need to move your code to before the onLike is called.
You're also attempting to get a bitmap from the cache of the entire layout, rather than the wanted ImageView here:
bm=contentLayout.getDrawingCache();
You'll want to get your current card view as a View, then, from my understanding of your code, the ID of your actual ImageView containing the expected bitmap is R.id.imgMeals, so I the suggest replacing the line:
bm=contentLayout.getDrawingCache();
with the following:
ImageView imageView = (ImageView) cardView.findViewById(R.id.imgMeals);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bm = drawable.getBitmap();
Move all of the below code from where you have it, to where I have marked //HERE!! in the following part of your code (or better, move it to a new method and call the method here).
// If the imageview of like is clicked
case R.id.imgLike: {
// HERE!!
// The imageview in the contentlayout will be swiped to the right
mSwipeView.likeCard();
break;
}
This is the code to me moved including the change I mention above:
View cardView = mSwipeView.getChildAt(mSwipeView.getChildCount() - 1);
ImageView imageView = (ImageView) cardView.findViewById(R.id.imgMeals);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bm = drawable.getBitmap();
OutputStream fOut = null;
try {
// Save on my sd card
File root = new File(Environment.getExternalStorageDirectory()
// Making a folder name Food Inspiration
+ File.separator + "Food Inspiration" + File.separator);
root.mkdirs();
File sdImageMainDirectory = null;
// Loop for having a different name for every image
int i = 0;
do {
sdImageMainDirectory = new File(root, "pic-" + i + ".png");
i++;
} while (sdImageMainDirectory.exists());
fOut = new FileOutputStream(sdImageMainDirectory);
// Updates the gallery of your phone with the folder and the "liked" images in it
MediaScannerConnection.scanFile(this, new String[] { sdImageMainDirectory.getAbsolutePath() }, null, null);
// If something goes wrong
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
// Compresses the actual bitmap image
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e){}

NullPointerException when retrieving data from sqlite database

ive stored some image names in a sqlite database.My code is supposed to retrieve all the imagenames and store it in a array and then assign the first image to an imageview based on its name.Im using UIL to set the images to the image view.
MY CODE
public class Locker extends Activity {
int index = 0, limit, tolerance = 40, state = 1;
String[] bgimg;
String[] ranimg;
int[] ActXCod;
int[] ActYCod;
ImageView image;
ImageLoader imageloader;
File Path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locker);
image = (ImageView) findViewById(R.id.imageView1);
SharedPreferences getprefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
String temp = getprefs.getString("ImageSeqNo", "4");
limit = Integer.parseInt(temp);
Path = getExternalFilesDir(null);
Constants cons = new Constants();
ranimg = cons.getImagePath(Path.toString());
imageloader = ImageLoader.getInstance();
try {
new Thread(new getData()).start();
imageloader.displayImage("file://" + Path.toString() + "/"
+ bgimg[index], image);
} catch (Exception e) {
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("ERROR");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
}
public boolean onTouchEvent(MotionEvent event) {
// MotionEvent object holds X-Y values
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int XCood = (int) event.getX();
int YCood = (int) event.getY();
int XMin = ActXCod[index] - tolerance, XMax = ActXCod[index]
+ tolerance, YMin = ActYCod[index] - tolerance, YMax = ActYCod[index]
+ tolerance;
/*
* String text = "You clicked at x = " + XCood + " and y = " +
* YCood; final Toast toast = Toast.makeText(this, text,
* Toast.LENGTH_SHORT); toast.show(); Handler handler = new
* Handler(); handler.postDelayed(new Runnable() {
*
* #Override public void run() { toast.cancel(); } }, 750);
*/
if (index < (limit - 1)) // loop to check number of images
{
// loop to check status
if ((state == 1)
&& (((XCood > XMin) && (XCood < XMax)) && ((YCood > YMin) && (YCood < YMax)))) {
index++;
imageloader.displayImage("file://" + Path.toString() + "/"
+ bgimg[index], image);
} else {
index++;
Random r = new Random();
int ran = r.nextInt(10 - 0);
imageloader.displayImage("file://" + ranimg[ran], image);
state = 0;
}
} else {
if (state == 1) {
Intent i = new Intent(Locker.this, Compare_Pattern.class);
startActivity(i);
finish();
} else {
new AlertDialog.Builder(this)
.setTitle("Failed Login Attempt")
.setMessage(
"Your previous login attempt has failed.Would you like to try again?")
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
// continue with delete
Intent intent = getIntent();
startActivity(intent);
finish();
}
})
.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
// do nothing
finish();
}
}).show();
}
}
}
return super.onTouchEvent(event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class getData implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
DataBaseHandler handler = new DataBaseHandler(
getApplicationContext());
handler.open();
ActXCod = handler.getXcod();
ActYCod = handler.getYcod();
bgimg = handler.getImg();
handler.close();
}
}
}
i tried debugging the code and its giving me a Java.lang.NullPointerException for bgimg[index] at the line imageloader.displayImage("file://" + Path.toString() + "/" + bgimg[index], image);. i cannot figure out why. Any help is gratefully accepted.
new Thread(new getData()).start();
imageloader.displayImage("file://" + Path.toString() + "/"
+ bgimg[index], image);
bgimg is not initialized yet. Even if you start your thread, it does not run and compelete initialization of bgimg immediately.
Move the code that requires the result of the thread code into the thread itself. You can use Activity.runOnUiThread() to move the execution back to UI thread from a background thread.

Android: clear the listview data on button click

In my app I have a listview where it is loading data based on the search keyword, now I want to clear the loaded data on button click.
#Override
protected void onPreExecute() {
SearchUtils searchUtils = null;
List<Place> searchResult = null;
String searchType = null;
Log.d(TAG, "onPreExecute start=");
// show your dialog
super.onPreExecute();
Log.d(TAG, "LoadMenuSearch isOldDataToLoad : " + isOldDataToLoad);
if(!this.isOldDataToLoad){
this.dialog.setCanceledOnTouchOutside(false);
this.dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
this.dialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
}
});
Button morerecords = (Button) activity.findViewById(R.id.morerecords);
morerecords.setVisibility(View.GONE);
morerecords.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "Do Nothing........................");
}
});
//morerecords.setVisibility(View.VISIBLE);
final Button closesearch = (Button) activity.findViewById(R.id.closesearch);
closesearch.setVisibility(View.VISIBLE);
closesearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ListView menuSearchListView = (ListView) activity
.findViewById(R.id.menusearchlist);
searchAdapter.clear();
searchAdapter.notifyDataSetChanged();
closesearch.setVisibility(View.GONE);
}
});
Here in the preexecute I have a button, now when I click the button loaded data should be clear and the listview should get refreshed.
my search adaptor
public SearchAdapter(Activity activity, int viewResourceId, int renderer,
double latitute, double longitute, String menuId,
ArrayList<Neighborhood> nhdDetails,
ArrayList<AttractionData> items, boolean isAddressBook,
boolean isRecommended) {
super(activity, viewResourceId, items);
streetView = new StreetViewUtils(activity);
streetView.loadHtml();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) (getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE));
view = inflater.inflate(renderer, null);
}
attractionData = items.get(position);
Log.d(TAG, "attractionData " + attractionData + " for position "
+ position);
TextView textName = (TextView) view.findViewById(R.id.textName);
TextView textAddress = (TextView) view.findViewById(R.id.textAddress);
TextView textPhone = (TextView) view.findViewById(R.id.textPhone);
addFavorite = (ImageView) view.findViewById(R.id.pinsave);
LinearLayout itemlayer = (LinearLayout) view
.findViewById(R.id.itemlayer);
itemlayer.setTag(attractionData);
textName.setText(attractionData.getfName());
if (!isRecommended) {
TextView mapidDisplay = (TextView) view.findViewById(R.id.mapid);
mapidDisplay.setTextSize(Constants.defaultFontSize + 2);
if (isAddressBook) {
mapidDisplay.setBackgroundColor(Color.YELLOW);
mapidDisplay.setTextColor(Color.BLACK);
} else {
mapidDisplay.setBackgroundColor(Color.RED);
mapidDisplay.setTextColor(Color.WHITE);
}
mapidDisplay.setTag(attractionData);
mapidDisplay.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
focusLication(v, event);
return true;
}
});
Log.d(TAG,
"attractionData.getLatitude() ----->"
+ attractionData.getLatitude()
+ " attractionData.getLongitude()---> "
+ attractionData.getLongitude());
if (attractionData.getLatitude() != 0
&& attractionData.getLongitude() != 0) {
mapidDisplay.setText(" " + abbrMapId + (position + 1) + " ");
mapidDisplay.setVisibility(View.VISIBLE);
} else {
mapidDisplay.setVisibility(View.GONE);
}
} else {
ImageView acceptRecommend = (ImageView) view
.findViewById(R.id.acceptRecommend);
ImageView rejectRecommend = (ImageView) view
.findViewById(R.id.rejectRecommend);
acceptRecommend.setVisibility(View.VISIBLE);
rejectRecommend.setVisibility(View.VISIBLE);
acceptRecommend.setTag(attractionData);
rejectRecommend.setTag(attractionData);
acceptRecommend.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
AttractionData data = (AttractionData) ((ImageView) v).getTag();
((CityPreferences) activity.getApplication()).updateRecommended(data);
items.remove(position);
notifyDataSetChanged();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
rejectRecommend.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
AttractionData data = (AttractionData) ((ImageView) v).getTag();
long id = data.getId();
((CityPreferences) activity.getApplication()).deleteSavedAttractions(data);
data.setStatus("unselect");
items.remove(position);
notifyDataSetChanged();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
}
textAddress.setText(attractionData.getAddress());
TextView distance = (TextView) view.findViewById(R.id.distance);
ImageView distanceDir = (ImageView) view
.findViewById(R.id.distancedirection);
Bitmap bitmap = BitmapFactory.decodeResource(activity.getResources(),
R.drawable.navigationdir);
float newRot = new Float(attractionData.getNavigationAngle());
Matrix matrix = new Matrix();
matrix.postRotate(newRot);
// Log.d(TAG, "Roating the Navigation Image : 01" +
// Constants.mOrientation[0]);
if (Constants.mOrientation != null && Constants.mOrientation.length > 0) {
double bearingToTarget = newRot + Constants.mOrientation[0];
double drawingAngle = Math.toRadians(bearingToTarget)
- (Math.PI / 2);
float cos = (float) Math.cos(drawingAngle);
float sin = (float) Math.sin(drawingAngle);
matrix.setSinCos(sin, cos);
Bitmap redrawnBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
distanceDir.setImageBitmap(redrawnBitmap);
// distanceDir.setRotation(90);
} else {
Bitmap redrawnBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
distanceDir.setImageBitmap(redrawnBitmap);
}
if (attractionData.getDistance() != null
&& !attractionData.getDistance().equals("")) {
distance.setText(attractionData.getDistance());
} else {
distance.setText("");
}
if (attractionData.getLatitude() != 0.00
&& attractionData.getLongitude() != 0.00) {
distanceDir.setVisibility(View.VISIBLE);
distance.setVisibility(View.VISIBLE);
} else {
distanceDir.setVisibility(View.GONE);
distance.setVisibility(View.GONE);
}
// Log.d(TAG, "end to search distance -->");
LinearLayout llReviews = (LinearLayout) view
.findViewById(R.id.reviewsrating);
llReviews.setVisibility(View.VISIBLE);
GridView gridview = (GridView) view.findViewById(R.id.ratingView);
TextView textRating = (TextView) view.findViewById(R.id.rating);
TextView textReviews = (TextView) view.findViewById(R.id.reviews);
textRating.setText("(" + attractionData.getRating() + ")");
gridview.setAdapter(new ImageAdapter(getContext(), attractionData
.getRating()));
// code for review
if (attractionData.getReview() != null
&& (attractionData.getReview().equals("1") || attractionData
.getReview().equals("0"))) {
textReviews.setText(attractionData.getReview() + " review");
} else if (attractionData.getReview() != null) {
textReviews.setText(attractionData.getReview() + " reviews");
} else {
textReviews.setText("0 review");
}
textReviews.setTag(attractionData.getReviewUrl());
textReviews.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String webURL = (String) v.getTag();
utils.openWebURL(v.getContext(), webURL);
}
});
if (Constants.isDefineNeighbourHood) {
addFavorite.setVisibility(View.GONE);
} else {
if (attractionData.getId() > 0) {
if (menuId != null && menuId.equalsIgnoreCase(Constants.menuFavouritePlaceId)) {
addFavorite.setImageResource(R.drawable.favorite_active);
addFavorite.setVisibility(View.GONE);
attractionData.setStatus("select");
EditAttraction editAttraction = new EditAttraction(activity, false);
itemlayer.setOnLongClickListener(editAttraction);
if (!Constants.isEysonly) {
Loginmyplaces loginmyplaces = new Loginmyplaces(activity);
itemlayer.setOnClickListener(loginmyplaces);
}
} else {
addFavorite.setImageResource(R.drawable.favorite_active);
addFavorite.setVisibility(View.VISIBLE);
attractionData.setStatus("select");
EditAttraction editAttraction = new EditAttraction(activity, true);
itemlayer.setOnLongClickListener(editAttraction);
}
} else {
addFavorite.setVisibility(View.VISIBLE);
addFavorite.setImageResource(R.drawable.favorite);
attractionData.setStatus("unselect");
EditAttraction editAttraction = new EditAttraction(activity,
true);
itemlayer.setOnLongClickListener(editAttraction);
}
}
// Log.d(TAG, "Constants.totalFavorite : status : " +
// attractionData.getStatus() + " for " + attractionData.getName());
addFavorite.setTag(attractionData);
addFavorite.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
AttractionData data = (AttractionData) ((ImageView) v)
.getTag();
ImageView currentpinsave = (ImageView) v
.findViewById(R.id.pinsave);
Log.d(TAG,
"Constants.totalFavorite : status : "
+ data.getStatus());
Log.d(TAG, "Constants.totalFavorite : Resource : "
+ currentpinsave);
if (data.getStatus() != null
&& data.getStatus().equalsIgnoreCase("select")) {
Log.d(TAG, "data.status " + data.getStatus());
currentpinsave.setImageResource(R.drawable.favorite);
currentpinsave.setTag(data);
long id = data.getId();
((CityPreferences) activity.getApplication())
.deleteSavedAttractions(data);
data.setStatus("unselect");
currentpinsave.setImageResource(R.drawable.favorite);
new DeleteFromConstance().execute(id);
} else {
Log.d(TAG, "data.status " + data.getStatus());
currentpinsave
.setImageResource(R.drawable.favorite_active);
currentpinsave.setTag(data);
data.setMenuId(menuId);
streetView.checkPhotoView(data);
((CityPreferences) activity.getApplication())
.saveMyAttractions(data, true);
data.setStatus("select");
utils.checkFavoriteCity(activity, data);
}
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
if (!isRecommended) {
if (attractionData.getImages() != null) {
Log.d(TAG, "ImageUtils --> inside blob saved");
ImageView placeImage = (ImageView) view
.findViewById(R.id.placeimage);
placeImage.setVisibility(View.VISIBLE);
placeImage.setImageBitmap(attractionData.getImages());
} else {
Log.d(TAG, "ImageUtils --> inside blob not saved");
ImageView placeImage = (ImageView) view
.findViewById(R.id.placeimage);
placeImage.setVisibility(View.GONE);
}
}
ImageView navigationImage = (ImageView) view
.findViewById(R.id.navigationImage);
ImageView streetViewImage = (ImageView) view
.findViewById(R.id.streetview);
if (attractionData.getLatitude() != 0
&& attractionData.getLongitude() != 0) {
navigationImage.setImageResource(R.drawable.navigation);
navigationImage.setTag(attractionData);
navigationImage.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (utils.isConnectionAvailable(v.getContext())) {
Intent intent = new Intent(v.getContext(), Navigator.class);
AttractionData data = (AttractionData) ((ImageView) v).getTag();
Bundle bundle = new Bundle();
// add data to bundle
bundle.putString("startlatitude", latitute + "");
bundle.putString("startlongitude", longitute + "");
bundle.putString("latitude", data.getLatitude() + "");
bundle.putString("longitude", data.getLongitude() + "");
intent.putExtras(bundle);
v.getContext().startActivity(new Intent(intent).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK));
} else {
Toast.makeText(v.getContext(), v.getContext().getResources().getString(R.string.noconnection), Toast.LENGTH_LONG).show();
}
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
streetViewImage.setTag(attractionData);
streetViewImage.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
AttractionData data = (AttractionData) v.getTag();
Location location = new Location("");
location.setLatitude(data.getLatitude());
location.setLongitude(data.getLongitude());
streetView.checkStreetView(location);
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}});
streetViewImage.setVisibility(View.VISIBLE);
navigationImage.setVisibility(View.VISIBLE);
} else {
streetViewImage.setVisibility(View.GONE);
navigationImage.setVisibility(View.GONE);
}
LinearLayout commentLayout = (LinearLayout) view
.findViewById(R.id.commentLayout);
if (attractionData.getComments() != null
&& !attractionData.getComments().trim().equals("")) {
commentLayout.setVisibility(View.VISIBLE);
TextView comment = (TextView) view.findViewById(R.id.comment);
comment.setText(attractionData.getComments());
} else {
commentLayout.setVisibility(View.GONE);
}
ImageView phImage = (ImageView) view.findViewById(R.id.phoneImage);
String phoneNo = attractionData.getPhoneNo();
if (attractionData.getMobileNo() != null
&& !attractionData.getMobileNo().equals("")
&& !attractionData.getMobileNo().equalsIgnoreCase("null")) {
if (phoneNo != null && !phoneNo.equals("")
&& !phoneNo.equalsIgnoreCase("null")) {
phoneNo = phoneNo + ",\n" + attractionData.getMobileNo();
} else {
phoneNo = attractionData.getMobileNo();
}
}
Log.d(TAG, "------------------> phoneNo " + phoneNo);
if (phoneNo != null && !phoneNo.equals("") && !phoneNo.equalsIgnoreCase("null")) {
textPhone.setText(phoneNo);
textPhone.setVisibility(View.VISIBLE);
phImage.setVisibility(View.VISIBLE);
phImage.setImageResource(R.drawable.phone);
phImage.setTag(phoneNo);
phImage.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
String phone = (String) ((ImageView) v).getTag();
Log.d(TAG, "onTouch phone--" + phone);
utils.dailPhone(v.getContext(), phone);
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
} else {
phImage.setVisibility(View.GONE);
textPhone.setVisibility(View.GONE);
}
LinearLayout htmllayout = (LinearLayout) view
.findViewById(R.id.htmllayout);
if (attractionData.getHtmlAttributions() != null
&& !attractionData.getHtmlAttributions().equals("")
&& !attractionData.getHtmlAttributions().equalsIgnoreCase(
"null")) {
htmllayout.setVisibility(View.VISIBLE);
TextView htmlAttributions = (TextView) view
.findViewById(R.id.htmlAttributions);
TextView htmlAttributionsLink = (TextView) view
.findViewById(R.id.htmlAttributionsLink);
htmlAttributions.setText(attractionData.getHtmlAttributions());
htmlAttributionsLink.setText(attractionData
.getHtmlAttributionsLink());
htmlAttributionsLink.setTag(attractionData);
htmlAttributionsLink.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
AttractionData data = (AttractionData) ((TextView) v)
.getTag();
utils.openWebURL(v.getContext(),
data.getHtmlAttributionsUrl());
new Intent(Intent.ACTION_VIEW);
return true;
}
});
} else {
htmllayout.setVisibility(View.GONE);
}
// ********************************************* changing for showing
// the zagat review and price level
String priceTag = attractionData.getPriceTag();
String zagatReview = attractionData.getZagatReview();
Log.d(TAG, "Extra Parameter Setup : " + attractionData.getfName()
+ " URL : " + attractionData.getReviewUrl());
Log.d(TAG, "Extra Parameter Setup : priceTag : " + priceTag
+ " zagatReview : " + zagatReview);
if (priceTag != null && !priceTag.equals("")) {
((TextView) view.findViewById(R.id.pricelevelvalue))
.setText(priceTag);
} else {
view.findViewById(R.id.pricelevelvalue).setVisibility(View.GONE);
}
if (zagatReview != null && !zagatReview.equals("")) {
view.findViewById(R.id.moredetail_review).setVisibility(
View.VISIBLE);
((TextView) view.findViewById(R.id.zagatreviewvalue))
.setText(zagatReview);
} else {
view.findViewById(R.id.moredetail_review).setVisibility(View.GONE);
}
Reservation reservation = attractionData.getReservation();
List<PlaceMenu> menus = attractionData.getMenu();
if ((reservation != null) || (menus != null && !menus.isEmpty())) {
view.findViewById(R.id.moredetail_menu_reservation).setVisibility(
View.VISIBLE);
TextView reservationTextView = (TextView) view
.findViewById(R.id.reservationvalues);
if (reservation != null && reservation.getName() != null
&& !reservation.getName().equals("")) {
Log.d(TAG,
"Extra Parameter Setup : reservation "
+ reservation.getName() + " URL : "
+ reservation.getUrl());
view.findViewById(R.id.reservation).setVisibility(View.VISIBLE);
reservationTextView.setVisibility(View.VISIBLE);
reservationTextView.setText(reservation.getName());
reservationTextView.setTag(reservation.getUrl());
reservationTextView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
utils.openWebURL(v.getContext(),
(String) ((TextView) v).getTag());
new Intent(Intent.ACTION_VIEW);
return true;
}
});
} else {
view.findViewById(R.id.reservation).setVisibility(View.GONE);
reservationTextView.setVisibility(View.GONE);
}
TextView placemenuTextView = (TextView) view
.findViewById(R.id.placemenu);
if (menus != null && !menus.isEmpty()) {
Log.d(TAG,
"Extra Parameter Setup : Menu Size : " + menus.size());
placemenuTextView.setVisibility(View.VISIBLE);
placemenuTextView.setTag(menus);
placemenuTextView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
List<PlaceMenu> placeMenu = (List<PlaceMenu>) ((TextView) v).getTag();
ArrayList<DialogData> data = new ArrayList<DialogData>();
for (int i = 0; i < placeMenu.size(); i++) {
DialogData dialogData = new DialogData();
dialogData.setName(placeMenu.get(i).getName());
dialogData.setValue(placeMenu.get(i).getUrl());
dialogData.setType("url");
data.add(dialogData);
}
utils.showPopupDailog(v.getContext(), data, "Menu");
new Intent(Intent.ACTION_VIEW);
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
} else {
placemenuTextView.setVisibility(View.GONE);
}
} else {
view.findViewById(R.id.moredetail_menu_reservation).setVisibility(
View.GONE);
}
if (attractionData.getHotelReview() != null) {
PlaceHotelReview hotelReview = null;
TextView textView = null;
textView = (TextView) view.findViewById(R.id.hotelreviewtext);
if (menuId != null && menuId.equals(Constants.menuHotelId)) {
textView.setText(R.string.hotelPricing);
} else {
textView.setText(R.string.hotelreview);
}
Log.d(TAG, "Hotel Review Step 02 : ");
LinearLayout rl = (LinearLayout) view
.findViewById(R.id.hotelreview);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
view.findViewById(R.id.hotelreview).setVisibility(View.VISIBLE);
rl.removeAllViews();
rl.addView(textView, lp);
for (int i = 0; i < attractionData.getHotelReview().size(); i++) {
hotelReview = attractionData.getHotelReview().get(i);
Log.d(TAG, "Hotel Review Step 03 : " + hotelReview);
textView = new TextView(activity);
Log.d(TAG, "Hotel Review Step 04 : " + hotelReview.getName());
Log.d(TAG, "Hotel Review Step 05 : " + hotelReview.getReviews());
textView.setText(hotelReview.getName().replaceAll("\"", ""));
if (i == attractionData.getHotelReview().size() - 1) {
textView.setPadding(5, 5, 0, 5);
} else if (i == attractionData.getHotelReview().size() - 1) {
textView.setPadding(5, 0, 0, 5);
} else {
textView.setPadding(5, 5, 0, 0);
}
textView.setTextColor(Color.parseColor("#0000ff"));
textView.setTag(hotelReview);
Log.d(TAG, "Hotel Review Step 05 : ");
textView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
PlaceHotelReview hotelReview = (PlaceHotelReview) v.getTag();
utils.openWebURL(v.getContext(), hotelReview.getUrl().replaceAll("\"", ""));
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
rl.addView(textView, lp);
}
} else {
view.findViewById(R.id.hotelreview).setVisibility(View.GONE);
}
TextView openCloseTime = (TextView) view
.findViewById(R.id.openclosedesc);
if (attractionData.getOpenCloseDesc() != null
&& !attractionData.getOpenCloseDesc().equals("")
&& !attractionData.getOpenCloseDesc().equalsIgnoreCase("null")) {
openCloseTime.setText(attractionData.getOpenCloseDesc());
} else {
openCloseTime.setVisibility(View.GONE);
}
itemlayer.setOnTouchListener(new DetectMotion(activity, isAddressBook));
if (position % 2 == 0)
view.setBackgroundResource(R.drawable.listshape);
else
view.setBackgroundResource(R.drawable.favoritebody);
return view;
}
private void focusLication(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
AttractionData ad = (AttractionData) v.getTag();
Constants.isMaptobeLoaded = true;
if (ad.getLatitude() != 0 && ad.getLongitude() != 0) {
if (Constants.isDefineNeighbourHood) {
if (Constants.focusLocationNH == null) {
Constants.focusLocationNH = new Location("");
}
Constants.focusLocationNH.setLatitude(ad.getLatitude());
Constants.focusLocationNH.setLongitude(ad.getLongitude());
if (Constants.myNeighborHoodLocation == null) {
Constants.myNeighborHoodLocation = new Location("");
}
Constants.myNeighborHoodLocation.setLatitude(ad
.getLatitude());
Constants.myNeighborHoodLocation.setLongitude(ad
.getLongitude());
} else {
if (Constants.focusLocation == null) {
Constants.focusLocation = new Location("");
}
Constants.focusLocation.setLatitude(ad.getLatitude());
Constants.focusLocation.setLongitude(ad.getLongitude());
}
activity.finish();
if (isAddressBook) {
Constants.isPABImportant = true;
activity.overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_out_left);
} else {
Constants.isPABImportant = false;
activity.overridePendingTransition(R.anim.slide_out_right,
R.anim.slide_in_right);
}
}
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
}
Any help is appreciated.
Try like this way
list.clear();
adpater.notifyDataSetChanged();
/// remove item from list.
adapter.clear();
adpater.notifyDataSetChanged();
Not all Adapters have a clear() method. ArrayAdapter does, but ListAdapter or SimpleAdapter doesn't
Just notify the listview after clearing the data of adapter i guess searchAdapter is your adapter . SearchAdapter is a custom adapter where you need to clear data based on type of adapter then call notifyDataSetChanged.
This is the code for clearing listview data on button click
Button yourbutton; // init it
yourButon.setOnClickListener(new OnClickListener(){
yourList.clear(); // this list which you hava passed in Adapter for your listview
yourAdapter.notifyDataSetChanged(); // notify to listview for refresh
});

Double Tapping on the textView

Eg.,
Welcome to Android World.
Now when I double tap on the space between "Welcome" and "to", the String from "to" to "World" should come in the next line.
That is,
Welcome <\n>
to Android World.
Similarly, when I double tap the space between "to" and "Android", it should be,
Welcome <\n>
to <\n>
Android World.
The first time it works, but the next time it force stops.
I don't know where I am going wrong. Probably it is not getting the onTouchListener properly.
Need Help.
linear_layout = (LinearLayout) findViewById(R.id.linearLayout);
mTextView = new TextView[10];
mTextView[i] = new TextView(this);
mTextView[i].setText("Hello Android Text View");
linear_layout.addView(mTextView[i]);
mTextView[i].setOnTouchListener(this);
mGestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
#Override
public void onLongPress(MotionEvent e) {
Log.d(TAG, "Long Press event");
Toast.makeText(getBaseContext(), "Long Press", Toast.LENGTH_LONG).show();
}
#Override
public boolean onDoubleTap(MotionEvent e) {
Log.d(TAG, "Double Tap event");
Toast.makeText(getBaseContext(), "Double Tap", Toast.LENGTH_LONG).show();
Log.i("Tag", "------------------------------ " + e.getX() + " " + e.getY());
Layout layout = ((TextView) view).getLayout();
int x = (int)e.getX();
int y = (int)e.getY();
if (layout!=null){
line = layout.getLineForVertical(y);
characterOffset = layout.getOffsetForHorizontal(line, x);
Log.i("index", ""+characterOffset);
}
String text = mTextView[i].getText().toString();
char[] char_txt = text.toCharArray();
int ascii_val = (int)text.charAt(characterOffset);
String rem_txt = "";
//if(ascii_val == 32) {
int n=characterOffset;
while(n < char_txt.length){
rem_txt += char_txt[n];
n++;
}
//}
i++;
String before_tap_txt = text.subSequence(0, characterOffset).toString();
mTextView[i-1].setText(before_tap_txt);
mTextView[i] = new TextView(GestureDetecterExampleActivity.this);
mTextView[i].setText(rem_txt);
linear_layout.addView(mTextView[i]);
return true;
}
#Override
public boolean onDown(MotionEvent e) {
return true;
}
});
mGestureDetector.setIsLongpressEnabled(true);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
view = v;
return mGestureDetector.onTouchEvent(event);
}
Log.d(TAG, "Double Tap event");
/* Toast.makeText(getBaseContext(), "Double Tap",
Toast.LENGTH_LONG).show();*/
Log.i("Tag",
"------------------------------ " + e.getX()
+ " " + e.getY());
Layout layout = ((TextView) view).getLayout();
int x = (int) e.getX();
int y = (int) e.getY();
if (layout != null) {
line = layout.getLineForVertical(y);
characterOffset = layout.getOffsetForHorizontal(
line, x);
Log.i("index", "" + characterOffset);
}
String text = mTextView[i].getText().toString();
char[] char_txt = text.toCharArray();
int ascii_val = (int) text.charAt(characterOffset);
String rem_txt = "";
if(ascii_val == 32) {
int n = characterOffset;
while (n < char_txt.length) {
rem_txt += char_txt[n];
n++;
}
// }
i++;
String before_tap_txt = text.subSequence(0,
characterOffset).toString();
mTextView[i - 1].setText(before_tap_txt.trim());
mTextView[i] = new TextView(
DoubleTapActivity.this);
mTextView[i].setText(rem_txt.trim());
mTextView[i].setOnTouchListener(DoubleTapActivity.this);
linear_layout.addView(mTextView[i]);
return true;
}
else
{
Toast.makeText(DoubleTapActivity.this, "" + text.charAt(characterOffset), Toast
.LENGTH_SHORT).show();
}
return false;
Place this code in ur double tap method.
comment if you need any help.

Categories

Resources