I have a drawing application and I have methods for saving pictures drawn. But I only get a black bitmap picture with the save button. Where is the problem ?
There is my xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/all"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
tools:context=".Circle"
>
<org.vkedco.mobappdev.draw_touch_drive_00001.krouzky
android:id="#+id/pntr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:tag="Painter" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView3"
android:layout_below="#+id/button4"
android:layout_marginTop="50dp"
android:text="value"
android:textColor="#color/white" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/button2"
android:text="Add" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Delete" />
<Button
android:id="#+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Save"
android:layout_marginTop="45dp"
android:layout_alignLeft="#+id/button3" />
<Button
android:id="#+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Clear"
android:layout_marginTop="45dp"
android:layout_alignRight="#+id/button3" />
<LinearLayout
android:orientation="vertical"
android:layout_height="match_parent"
android:id="#+id/linearLayout"
android:layout_width="match_parent" />
And my main Activity:
public class aktivita extends Activity{
Button btn;
public LinearLayout mContent;
krouzky mTicTacToeView = null;
public static String tempDir;
public File mypath;
public static Bitmap mBitmap;
public static int width;
public static int height;
public static float x;
public static float y;
public static float X;
public static float Y;
public static double vzdalenost;
public String current = null;
private String uniqueId;
public krouzky mSignature;
public View mView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.zaznam_ran);
krouzky.t = 0;
File directory = new File(Environment.getExternalStorageDirectory() + "/Images");
if(!directory.exists())
directory.mkdir();
uniqueId = getTodaysDate() + "_" + getCurrentTime();
current = uniqueId + ".png";
mypath= new File(directory,current);
mContent = (LinearLayout) findViewById(R.id.linearLayout);
mSignature = new krouzky(this, null);
mSignature.setBackgroundColor(Color.TRANSPARENT);
mContent.addView(mSignature, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
mView = mContent;
Display display = getWindowManager().getDefaultDisplay();
width = (display.getWidth());
height = (display.getHeight());
mTicTacToeView = (krouzky) this.findViewById(R.id.pntr);
Button btn6 = (Button) findViewById(R.id.button6);
btn6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag", "Panel Saved");
mView.setDrawingCacheEnabled(true);
save(v);
}
});
}
private boolean prepareDirectory()
{
try
{
if (makedirs())
{
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(this, "Could not initiate File System.. Is Sdcard mounted properly?", 1000).show();
return false;
}
}
private boolean makedirs()
{
File tempdir = new File(tempDir);
if (!tempdir.exists())
tempdir.mkdirs();
if (tempdir.isDirectory())
{
File[] files = tempdir.listFiles();
for (File file : files)
{
if (!file.delete())
{
System.out.println("Failed to delete " + file);
}
}
}
return (tempdir.isDirectory());
}
method for saving
public void save(View v)
{
Log.v("log_tag", "Width: " + v.getWidth());
Log.v("log_tag", "Height: " + v.getHeight());
if(mBitmap == null)
{
mBitmap = Bitmap.createBitmap (width, height, Bitmap.Config.RGB_565);
}
Canvas canvas = new Canvas(mBitmap);
try
{
FileOutputStream mFileOutStream = new FileOutputStream(mypath);
v.draw(canvas);
mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
mFileOutStream.flush();
mFileOutStream.close();
}
catch(Exception e)
{
Log.v("log_tag", e.toString());
}
}
My problem, was resolved, but I have one small detail. My application get down, when I change my xml. to this.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
tools:context=".Circle" >
<org.vkedco.mobappdev.draw_touch_drive_00001.krouzky
android:id="#+id/pntr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:tag="Painter" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/button2"
android:text="Add" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Delete" />
<Button
android:id="#+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Save"
android:layout_marginTop="45dp"
android:layout_alignLeft="#+id/button3" />
<Button
android:id="#+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Clear"
android:layout_marginTop="45dp"
android:layout_alignRight="#+id/button3" />
<LinearLayout
android:orientation="vertical"
android:layout_height="match_parent"
android:id="#+id/linearLayout"
android:layout_width="match_parent" >
</LinearLayout>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/button6"
android:layout_marginTop="21dp"
android:text="value"
android:textColor="#color/blue" />
Try this:
- find your parent view
RelativeLayout holder = (RelativeLayout) findViewById(R.id.all);
- And call loadBitmapFromView(holder).
public static Bitmap loadBitmapFromView(View v) {
DisplayMetrics dm = getResources().getDisplayMetrics();
v.measure(MeasureSpec.makeMeasureSpec(dm.widthPixels, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(dm.heightPixels, MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
((RelativeLayout) v).setGravity(Gravity.CENTER);
Bitmap returnedBitmap = Bitmap.createBitmap(v.getMeasuredWidth(),
v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(returnedBitmap);
v.draw(c);
return returnedBitmap;
}
Actually You are passing the view (v) of your Button btn6 in method save(v)- Pass linear layout object which is mcontent or mView, then that would be save(mContent), This will solve your problem
You can try this method also-
Pass your parent layout or view in method-
Bitmap file = save(mcontent);
Bitmap save(View v)
{
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
You can use View.getDrawingCache()
Before it you should call View.setDrawingCache(true);
I've created a cutom component that extends GroupView and used this method to save this layout to a bitmap.
public Bitmap createBitmap() {
//Log.d("Pin", "Image W ["+this.getWidth()+"] x H ["+this.getHeight()+"]");
Bitmap b = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.RGB_565);
Canvas c = new Canvas(b);
this.draw(c);
return b;
}
Hope it helps you. If you want to save your layout you should change this with the entire layout you want to save
Related
The program is supposed to run getCurrentLocation and then set the textView "coordinates" to the value of the coordinates called. That text view is part of a pager view that draws from a separate .xml file than the main layout "activity_main".
public class MainActivity extends AppCompatActivity
{
CardAdapter CardAdapter;
String coordinatesFinal;
FusedLocationProviderClient fusedLocationProviderClient;
TextView coordinates;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
getCurrentLocation();
}else
{
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},100);
}
setupCardItems();
ViewPager2 CardViewPager = findViewById(R.id.cardViewPager);
CardViewPager.setAdapter(CardAdapter);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
if (requestCode == 100 & grantResults.length > 0 && (grantResults[0] + grantResults[1]) == PackageManager.PERMISSION_GRANTED)
{
getCurrentLocation();
}else
{
Toast.makeText(getApplicationContext(), "Permission denied.",Toast.LENGTH_SHORT).show();
}
}
#SuppressLint("MissingPermission")
public void getCurrentLocation()
{
coordinates = findViewById(R.id.coordinates);
LocationManager locationManager = (LocationManager) getSystemService
(
Context.LOCATION_SERVICE
);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
{
fusedLocationProviderClient.getLastLocation().addOnCompleteListener(task ->
{
Location location = task.getResult();
if (location != null)
{
coordinates.setText(location.getLatitude()+", "+location.getLongitude());
}else
{
LocationRequest locationRequest = new LocationRequest().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(10000).setFastestInterval(1000).setNumUpdates(1);
LocationCallback locationCallback = new LocationCallback()
{
#Override
public void onLocationResult(LocationResult locationResult)
{
Location location1 = locationResult.getLastLocation();
coordinatesFinal = location1.getLatitude()+", "+location1.getLongitude();
}
};
fusedLocationProviderClient.requestLocationUpdates(locationRequest,locationCallback, Looper.myLooper());
}
});
}else
{
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
}
//card view
private void setupCardItems()
{
List<CardItem> CardItems = new ArrayList<>();
CardItem itemPageOne = new CardItem();
itemPageOne.setLocation("Home");
itemPageOne.setTemp("60°f");
itemPageOne.setWeatherDesc("Cloudy");
itemPageOne.setWeatherIcon(R.drawable.cloud);
itemPageOne.setHum("75%");
itemPageOne.setVis("10");
itemPageOne.setPrecip("50%");
itemPageOne.setDew("40°f");
itemPageOne.setCloud("80%");
itemPageOne.setFog("75%");
CardItem itemPageTwo = new CardItem();
itemPageTwo.setLocation("Madison");
itemPageTwo.setTemp("60°f");
itemPageTwo.setWeatherDesc("Sunny");
itemPageTwo.setWeatherIcon(R.drawable.sun);
itemPageTwo.setHum("75%");
itemPageTwo.setVis("10");
itemPageTwo.setPrecip("50%");
itemPageTwo.setDew("40°f");
itemPageTwo.setCloud("80%");
itemPageTwo.setFog("75%");
CardItem itemPageThree = new CardItem();
itemPageThree.setLocation("Milwaukee");
itemPageThree.setTemp("60°f");
itemPageThree.setWeatherDesc("Rainy");
itemPageThree.setWeatherIcon(R.drawable.rain);
itemPageThree.setHum("75%");
itemPageThree.setVis("10");
itemPageThree.setPrecip("50%");
itemPageThree.setDew("40°f");
itemPageThree.setCloud("80%");
itemPageThree.setFog("75%");
CardItems.add(itemPageOne);
CardItems.add(itemPageTwo);
CardItems.add(itemPageThree);
CardAdapter = new CardAdapter(CardItems);
}
}
I have narrowed it down to the line that doesn't work properly:
coordinates.setText(location.getLatitude()+", "+location.getLongitude());
I have tested the exact same line as above, only using a textView from inside activity main, which works just fine. Any help is greatly appreciated.
Edit: The file actually does crash, I mistakenly said it didn't, and I added both .xml Files:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_height="match_parent"
android:background="#566D8F"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/topBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:paddingTop="15dp"
android:paddingBottom="15dp">
<ImageButton
android:id="#+id/settingsBar2"
android:layout_width="27sp"
android:layout_height="27sp"
android:layout_gravity="left"
android:layout_marginStart="20sp"
android:layout_marginEnd="70sp"
android:background="#color/background"
android:cropToPadding="true"
android:scaleType="fitCenter" />
<TextView
android:id="#+id/homeName"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:fontFamily="sans-serif-condensed-light"
android:gravity="center_horizontal"
android:maxLines="1"
android:text="#string/app_name"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:typeface="normal" />
<ImageButton
android:id="#+id/settingsBar"
android:layout_width="27sp"
android:layout_height="27sp"
android:layout_gravity="right"
android:layout_marginStart="70sp"
android:layout_marginEnd="20sp"
android:background="#drawable/settings_handle"
android:cropToPadding="true"
android:scaleType="fitCenter" />
</LinearLayout>
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/cardViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toBottomOf="#+id/topBar" />
</androidx.constraintlayout.widget.ConstraintLayout>
item_container_card.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="20dp">
<androidx.cardview.widget.CardView
android:id="#+id/pagerCard"
android:layout_width="match_parent"
android:layout_height="440dp"
android:layout_margin="20dp"
app:cardBackgroundColor="#EAC0A0"
app:cardCornerRadius="30dp"
app:cardElevation="20dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/locationName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed-medium"
android:gravity="center"
android:textColor="#color/white"
android:textSize="18sp" />
<TextView
android:id="#+id/coordinates"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed-light"
android:gravity="center"
android:textColor="#color/white"
android:textSize="12sp" />
<TextView
android:id="#+id/temperature"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-black"
android:gravity="center"
android:textColor="#color/white"
android:textSize="50sp" />
<TextView
android:id="#+id/weatherDesc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed-light"
android:gravity="center"
android:textColor="#color/white"
android:textSize="12sp" />
<ImageView
android:id="#+id/imageOnboarding"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_margin="15dp"
android:adjustViewBounds="true"
android:contentDescription="#string/app_name" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<TextView
android:id="#+id/humidity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-light"
android:paddingLeft="30sp"
android:paddingBottom="5sp"
android:text="Humidity"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/humVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-medium"
android:paddingStart="10sp"
android:paddingEnd="15sp"
android:paddingBottom="5sp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/visibility"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed-light"
android:paddingStart="15sp"
android:paddingEnd="10sp"
android:paddingBottom="5sp"
android:text="Visibility"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/visVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-medium"
android:paddingStart="10sp"
android:paddingRight="30sp"
android:paddingBottom="5sp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<TextView
android:id="#+id/precipitation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-light"
android:paddingLeft="30sp"
android:paddingTop="5sp"
android:paddingBottom="5sp"
android:text="Precip. "
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/precipVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-medium"
android:paddingStart="10sp"
android:paddingTop="5sp"
android:paddingEnd="15sp"
android:paddingBottom="5sp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/dewPoint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed-light"
android:paddingStart="15sp"
android:paddingTop="5sp"
android:paddingBottom="5sp"
android:text="Dew Point"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/dewVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-medium"
android:paddingStart="10sp"
android:paddingTop="5sp"
android:paddingRight="30sp"
android:paddingBottom="5sp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<TextView
android:id="#+id/cloud"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-light"
android:paddingLeft="30sp"
android:paddingTop="5sp"
android:paddingBottom="5sp"
android:text="Cloud"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/cloudVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-medium"
android:paddingStart="10sp"
android:paddingTop="5sp"
android:paddingEnd="15sp"
android:paddingBottom="5sp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/fog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed-light"
android:paddingStart="15sp"
android:paddingTop="5sp"
android:paddingBottom="5sp"
android:text="Fog"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/fogVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-medium"
android:paddingStart="10sp"
android:paddingTop="5sp"
android:paddingEnd="30sp"
android:paddingBottom="5sp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</TableRow>
</TableLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
Edit 2: CardAdapter.java and CardItem.java
CardAdapter.java:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.cardViewHolder>
{
private List<CardItem> CardItems;
public CardAdapter(List<CardItem> CardItems) {
this.CardItems = CardItems;
}
#NonNull
#Override
public cardViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new cardViewHolder(
LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_container_card, parent, false
)
);
}
#Override
public void onBindViewHolder(#NonNull cardViewHolder holder, int position) {
holder.setCardData(CardItems.get(position));
}
#Override
public int getItemCount() {
return CardItems.size();
}
class cardViewHolder extends RecyclerView.ViewHolder
{
private TextView locationText;
private TextView weatherDesc;
private ImageView weatherIcon;
private TextView tempVal;
private TextView humVal;
private TextView visVal;
private TextView precipVal;
private TextView dewVal;
private TextView cloudVal;
private TextView fogVal;
public cardViewHolder(#NonNull View itemView)
{
super(itemView);
locationText = itemView.findViewById(R.id.locationName);
weatherDesc = itemView.findViewById(R.id.weatherDesc);
weatherIcon = itemView.findViewById(R.id.imageOnboarding);
tempVal = itemView.findViewById(R.id.temperature);
humVal = itemView.findViewById(R.id.humVal);
visVal = itemView.findViewById(R.id.visVal);
precipVal = itemView.findViewById(R.id.precipVal);
dewVal = itemView.findViewById(R.id.dewVal);
cloudVal = itemView.findViewById(R.id.cloudVal);
fogVal = itemView.findViewById(R.id.fogVal);
}
void setCardData(CardItem CardItem)
{
locationText.setText(CardItem.getLocation());
weatherDesc.setText(CardItem.getWeatherDesc());
weatherIcon.setImageResource(CardItem.getWeatherIcon());
tempVal.setText(CardItem.getTemp());
humVal.setText(CardItem.getHum());
visVal.setText(CardItem.getVis());
precipVal.setText(CardItem.getPrecip());
dewVal.setText(CardItem.getDew());
cloudVal.setText(CardItem.getCloud());
fogVal.setText(CardItem.getFog());
}
}
}
CardItem.java:
package com.example.viewpagertest;
public class CardItem
{
private int weatherIcon;
private String location;
private String temp;
private String weatherDesc;
private String hum;
private String vis;
private String precip;
private String dew;
private String cloud;
private String fog;
//weather icon
public int getWeatherIcon() {
return weatherIcon;
}
public void setWeatherIcon(int weatherIcon) {
this.weatherIcon = weatherIcon;
}
//location title
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
//temperature value
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
//weather description
public String getWeatherDesc() {
return weatherDesc;
}
public void setWeatherDesc(String weatherDesc) {
this.weatherDesc = weatherDesc;
}
//humidity value
public String getHum() {
return hum;
}
public void setHum(String hum) {
this.hum = hum;
}
//visibility value
public String getVis() {
return vis;
}
public void setVis(String vis) {
this.vis = vis;
}
//precipitation value
public String getPrecip() {
return precip;
}
public void setPrecip(String precip) {
this.precip = precip;
}
//dew point value
public String getDew() {
return dew;
}
public void setDew(String dew) {
this.dew = dew;
}
//cloud value
public String getCloud() {
return cloud;
}
public void setCloud(String cloud) {
this.cloud = cloud;
}
//fog value
public String getFog() {
return fog;
}
public void setFog(String fog) {
this.fog = fog;
}
}
Here's the Console when running a debugger with the breakpoint at
coordinates.setText(location.getLatitude()+", "+location.getLongitude());
The whole console breaks the character limit so here's a document with the console text.
Console Text
if (location != null)
{
// coordinates.setText(location.getLatitude()+", "+location.getLongitude());
cardAdapter.setCoordinates(0 /*the cardItem number you want to update*/, location.getLatitude()+", "+location.getLongitude());
}
Since the coordinates TextView is in your item xml, you will not be able to address it from the root of your MainActivity, but from your item.
Update
Thanks for adding the Adapter code:
Easiest would be to create a method in your adapter like the following:
setCoordinates(int position, String coords) {
holders.get(position).itemView.findViewById(R.id.coordinates).setText(coords);
}
To be able to access the holders on runtime, add the following:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.cardViewHolder>
{
private List<CardItem> cardItems;
private List<CardViewHolder> holders;
....
#Override
public cardViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
CardViewHolder holder = new cardViewHolder(
LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_container_card, parent, false
)
);
holders.add(holder);
return holder;
}
Another option would be to add the field coordinates to your CardItem and write the setCoordinates method like so:
setCoordinates(int position, String coords) {
cardItems.get(position).setCoordinates(coords);
notifyDataSetChanged(); // to reload the holders, only notifying the specific position will be faster to reload only the changed holder
}
You need to update the adapter items by creating a method in CardAdapter and calling it from main activity as below -
Create this method in your adapter class
public void updateAdapter(List<CardItem> CardItems) {
this.CardItems = CardItems;
notifyDataSetChanged();
}
Replace below line
CardAdapter = new CardAdapter(CardItems);
With this one
CardAdapter.updateAdapter(CardItems);
I have to make a listview from database and i want to put a image that is clickable in my list.I use CursorAdapter for it,but my image does not show on my list.Here is my BooksCursorAdapter
public class BooksCursorAdapter extends CursorAdapter {
public BooksCursorAdapter(Context context, Cursor c) {
super(context, c, 0 );
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.books_list_item, parent, false);
}
#Override
public void bindView(View view,final Context context, Cursor cursor) {
TextView productText = view.findViewById(R.id.productText);
TextView priceText = view.findViewById(R.id.priceText);
TextView quantityText = view.findViewById(R.id.quantityText);
ImageView shopButton = view.findViewById(R.id.shop_button);
int productColumnIndex = cursor.getColumnIndex(BooksContract.BooksEntry.COLUMN_BOOKS_PRODUCT);
int priceColumnIndex = cursor.getColumnIndex(BooksContract.BooksEntry.COLUMN_BOOKS_PRICE);
final int quantityColumnIndex = cursor.getColumnIndex(BooksContract.BooksEntry.COLUMN_BOOKS_QUANTITY);
String bookProduct = cursor.getString(productColumnIndex);
String bookPrice = cursor.getString(priceColumnIndex);
final int bookQuantity = cursor.getInt(quantityColumnIndex);
productText.setText(bookProduct);
priceText.setText(bookPrice);
quantityText.setText(Integer.toString(bookQuantity));
int idColumnIndex = cursor.getColumnIndex(BooksContract.BooksEntry._ID);
final int booksId = cursor.getInt(idColumnIndex);
shopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri currentUri = ContentUris.withAppendedId(BooksContract.BooksEntry.CONTENT_URI, booksId);
makeSale(context, bookQuantity, currentUri);
}
});
}
private void makeSale(Context context, int bookQuantity, Uri uri) {
if (bookQuantity == 0) {
Toast.makeText(context, R.string.no_books, Toast.LENGTH_SHORT).show();
} else {
int newQuantity = bookQuantity - 1;
ContentValues values = new ContentValues();
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_QUANTITY, newQuantity);
context.getContentResolver().update(uri, values, null, null);
}
}
}
Everything works fine and how it should be only that my image is not showing.
My book_list_item.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="333dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/activity_margin">
<TextView
android:id="#+id/productText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-medium"
android:textAppearance="?android:textAppearanceMedium"
android:textColor="#2B3D4D" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/priceText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textAppearance="?android:textAppearanceSmall"
android:textColor="#AEB6BD"
android:padding="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/currencyTextList" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/quantityTextList"
android:padding="5dp"/>
<TextView
android:id="#+id/quantityText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textAppearance="?android:textAppearanceSmall"
android:textColor="#AEB6BD" />
</LinearLayout>
</LinearLayout>
<ImageView
android:layout_width="52dp"
android:layout_height="match_parent"
android:src="#drawable/shop_button"
android:id="#+id/shop_button"/>
</LinearLayout>
The image appears in my preview but not on my phone.I want to display an image stored on xml, that I can click on.
I did what #crammeur said, in second LinearLayout i replaced android:layout_width="333dp" with android:layout_width="0dp" and add android:layout_weight="1"
I'm trying to draw a circle in the middle of an ImageView. Below is my UI code.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/white">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_weight="2"
android:id="#+id/bluh">
<ImageView
android:id="#+id/image_background"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:layout_weight="2"
android:src="#drawable/hhh" />
</LinearLayout>
<LinearLayout
android:id="#+id/l22Parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/bluh"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/step18button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="39dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/step18textView"
android:layout_marginLeft="3dp"
android:layout_weight="1"
android:text="1"
android:textSize="13dp" />
<Button
android:id="#+id/step18button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="39dp"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/step18button1"
android:layout_marginLeft="3dp"
android:layout_toEndOf="#+id/step18button1"
android:layout_toRightOf="#+id/step18button1"
android:layout_weight="1"
android:text="2"
android:textSize="13dp" />
<Button
android:id="#+id/step18button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="39dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/step18button2"
android:layout_marginLeft="3dp"
android:layout_toEndOf="#+id/step18button2"
android:layout_toRightOf="#+id/step18button2"
android:layout_weight="1"
android:text="3"
android:textSize="13dp" />
<Button
android:id="#+id/step18button4"
style="?android:attr/buttonStyleSmall"
android:layout_width="39dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/step18button3"
android:layout_marginLeft="3dp"
android:layout_toEndOf="#+id/step18button3"
android:layout_toRightOf="#+id/step18button3"
android:layout_weight="1"
android:text="4"
android:textSize="13dp" />
<Button
android:id="#+id/step18button5"
style="?android:attr/buttonStyleSmall"
android:layout_width="39dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/step18button4"
android:layout_marginLeft="3dp"
android:layout_toEndOf="#+id/step18button4"
android:layout_toRightOf="#+id/step18button4"
android:layout_weight="1"
android:text="5"
android:textSize="13dp" />
<Button
android:id="#+id/step18button6"
style="?android:attr/buttonStyleSmall"
android:layout_width="39dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/step18button5"
android:layout_marginLeft="3dp"
android:layout_toEndOf="#+id/step18button5"
android:layout_toRightOf="#+id/step18button5"
android:layout_weight="1"
android:text="6"
android:textSize="13dp" />
<Button
android:id="#+id/step18button7"
style="?android:attr/buttonStyleSmall"
android:layout_width="39dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/step18button6"
android:layout_marginLeft="3dp"
android:layout_toEndOf="#+id/step18button6"
android:layout_toRightOf="#+id/step18button6"
android:layout_weight="1"
android:text="7"
android:textSize="13dp" />
<Button
android:id="#+id/step18button8"
style="?android:attr/buttonStyleSmall"
android:layout_width="39dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/step18button7"
android:layout_marginLeft="3dp"
android:layout_toEndOf="#+id/step18button7"
android:layout_toRightOf="#+id/step18button7"
android:layout_weight="1"
android:text="8"
android:textSize="13dp" />
<Button
android:id="#+id/step18button9"
style="?android:attr/buttonStyleSmall"
android:layout_width="39dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/step18button8"
android:layout_marginLeft="3dp"
android:layout_toEndOf="#+id/step18button8"
android:layout_toRightOf="#+id/step18button8"
android:layout_weight="1"
android:text="9"
android:textSize="13dp" />
</LinearLayout>
</LinearLayout>
The generated UI is below
Below is my Fragment class
/**
* Created by user on 5/12/2016.
*/
public class GeneralizationFragment extends Fragment {
Context context;
private ImageView imageView;
private int width;
private int height;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.generalization_fragment, container, false);
createBitMap(v);
return v;
}
public static GeneralizationFragment newInstance() {
GeneralizationFragment f = new GeneralizationFragment();
Bundle b = new Bundle();
f.setArguments(b);
return f;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser) {
Activity a = getActivity();
if(a != null) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
private void createBitMap(final View v) {
BitmapFactory.Options myOptions = new BitmapFactory.Options();
myOptions.inDither = true;
myOptions.inScaled = true;
myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important
myOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.hhh, myOptions);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.BLUE);
Bitmap workingBitmap = Bitmap.createBitmap(bitmap);
Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
imageView = (ImageView)v.findViewById(R.id.image_background);
ViewTreeObserver vto = imageView.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
imageView.getViewTreeObserver().removeOnPreDrawListener(this);
height = imageView.getMeasuredHeight();
width = imageView.getMeasuredWidth();
Log.d("GENERALIZED", "Width:" + width);
return true;
}
});
float radius = (float) (width-(width*0.2));
DisplayMetrics displaymetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
Canvas canvas = new Canvas(mutableBitmap);
canvas.drawCircle(100, 100, 60, paint);
imageView.setAdjustViewBounds(true);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(mutableBitmap);
}
}
However I am not able to draw the circle (or the circle is not visible) until I remove imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); from my code. However that part is mandetory for me.
Also I have no idea of drawing it in the center.
I am inserting my List in a ListView, Which has some constant image and dynamic images with text.
So I wrote my CustomListViewAdapter, but when I am calling this I am getting NULL pointer exception at
holder.desc.setText(EventItems.getDesc());
in CustomListViewAdapterForEvent.
Here is my complete code.
Events.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/drop_shadow"
tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_below="#+id/imageView2"
android:orientation="vertical" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="343dp"
android:cacheColorHint="#515151"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:fadeScrollbars="false"
android:fastScrollEnabled="true"
android:scrollX="0px"
android:scrollY="8px"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbarSize="20dip"
android:scrollbarStyle="outsideOverlay"
android:scrollbars="vertical"
android:smoothScrollbar="true" >
</ListView>
</LinearLayout>
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:scaleType="fitXY"
android:src="#drawable/cat_header" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView2"
android:layout_alignLeft="#+id/imageView2"
android:layout_alignRight="#+id/imageView2"
android:layout_alignTop="#+id/imageView2" >
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".20"
android:src="#drawable/menu_icon1" />
<ImageView
android:id="#+id/imageView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".20"
android:src="#drawable/add_friend" />
<ImageView
android:id="#+id/imageView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".20"
android:src="#drawable/message_icon" />
<ImageView
android:id="#+id/imageView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".20"
android:src="#drawable/dollar_3d" />
<ImageView
android:id="#+id/imageView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".20"
android:src="#drawable/friend_icons" />
</LinearLayout>
</RelativeLayout>
EventList.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/transparent" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<ImageView
android:id="#+id/eventImage"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:contentDescription="#drawable/ic_launcher3"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/sweetIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:contentDescription="#drawable/ic_launcher3"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:scaleType="fitXY"
android:src="#drawable/aweet_icon" />
<TextView
android:id="#+id/sweetNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="sweetNo" />
<ImageView
android:id="#+id/facebookIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher1" />
<ImageView
android:id="#+id/googleIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher1" />
<ImageView
android:id="#+id/tweeterIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher1" />
<ImageView
android:id="#+id/pIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher1" />
</LinearLayout>
<TextView
android:id="#+id/eventDesc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="38dp"
android:text="Event Description" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/iAmThereIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_weight="0.25"
android:scaleType="fitXY"
android:src="#drawable/i_m_there_icon" />
<ImageView
android:id="#+id/maybeIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.25"
android:scaleType="fitXY"
android:src="#drawable/may_be_icon" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
CustomListViewAdapterForEvent.java
public class CustomListViewAdapterForEvent extends ArrayAdapter<EventItems> {
Context context;
public CustomListViewAdapterForEvent(Context context, int resourceId,
List<EventItems> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView eventImage;
TextView sweetNo;
TextView desc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.e("TAG ", "1111111111111111");
EventItems EventItems = getItem(position);
Log.e("TAG ", "2222222222222222222");
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
Log.e("TAG ", "3333333333333333333");
if (convertView == null) {
Log.e("TAG ", "444444444444444444444");
convertView = mInflater.inflate(R.layout.event_list, null);
holder = new ViewHolder();
holder.desc = (TextView) convertView.findViewById(R.id.desc);
holder.sweetNo = (TextView) convertView.findViewById(R.id.sweetNo);
holder.eventImage = (ImageView) convertView.findViewById(R.id.eventImage);
Log.e("TAG ", "5555555555555555");
convertView.setTag(holder);
} else{
Log.e("TAG ", "6666666666666666");
holder = (ViewHolder) convertView.getTag();
}
Log.e("TAG ", "77777777777777777777777");
holder.desc.setText(EventItems.getDesc());
Log.e("TAG ", "88888888888888888");
holder.sweetNo.setText(EventItems.getSweetNo());
holder.eventImage.setImageBitmap(EventItems.getEventImage());
return convertView;
}
}
EventItems.java
import android.graphics.Bitmap;
public class EventItems {
private Bitmap eventImage;
private String sweetNo;
private String desc;
public EventItems(Bitmap eventImage, String sweetNo, String desc) {
this.eventImage = eventImage;
this.sweetNo = sweetNo;
this.desc = desc;
}
public Bitmap getEventImage() {
return eventImage;
}
public void setEventImage(Bitmap eventImage) {
this.eventImage = eventImage;
}
public String getSweetNo() {
return sweetNo;
}
public void setSweetNo(String sweetNo) {
this.sweetNo = sweetNo;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
Events.java
public class Events extends Activity {
ListView listView;
List<EventItems> rowItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.events);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final AlertDialog ad=new AlertDialog.Builder(this).create();
rowItems = new ArrayList<EventItems>();
Bitmap bm =getImageBitmap("http://192.168.1.5/Upload/Thumbnail/1/iqygbbfn.jpg");
EventItems item = new EventItems(bm,"hi", "ji");
rowItems.add(item);
listView = (ListView) findViewById(R.id.list);
CustomListViewAdapterForEvent adapter = new CustomListViewAdapterForEvent(this,
R.layout.event_list, rowItems);
listView.setAdapter(adapter);
}
//Function for getting image from URL
private Bitmap getImageBitmap(String url)
{
Bitmap bm = null;
try
{
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e)
{
Log.e("TAG", "Error getting bitmap", e);
}
return bm;
}
}
Take a look on your EventList.xml, you have no element with id desc there, that is why you get null here (but you have eventDesc instead):
holder.desc = (TextView) convertView.findViewById(R.id.desc);
I believe it's just a typo and the correct line should be as following:
holder.desc = (TextView) convertView.findViewById(R.id.eventDesc);
P.S. Please read how to use debugger, it will make your life easier - placing a lot of Log objects is not the best solution for finding error.
Change this
holder.desc = (TextView) convertView.findViewById(R.id.desc);
To
holder.desc = (TextView) convertView.findViewById(R.id.eventDesc);
in your getView(....) into CustomListViewAdapterForEvent
I have 4 buttons in my android app activity. This is what it looks like:
As you can see, the textViews at the bottom of the screen display the x and y coordinates. The coordinates are in reference to a relative layout. (See below given code)
Now, what I want to do is get the x and y coordinates of the 4 buttons at runtime and then figure out if my finger is touching the buttons while moving or not. In simple words, I want to press the buttons by swiping my finger over them instead of lifting and touching. How can I achieve it? I want to implement it in my piano application.
I was able to get the coordinates on screen and they change as I move my finger.
So, my question is How can I get the coordinates of the buttons and detect if my finger is swiping above them?:
XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:id="#+id/relativelayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Y Cord : "
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp"
android:id="#+id/textView"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="X Cord : "
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp"
android:id="#+id/textView2"
android:layout_above="#+id/textView"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/textView3"
android:textColor="#000000"
android:layout_below="#+id/textView2"
android:layout_toRightOf="#+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/textView4"
android:textColor="#000000"
android:layout_marginBottom="10dp"
android:layout_above="#+id/textView"
android:layout_toRightOf="#+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:textColor="#000000"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:textColor="#000000"
android:id="#+id/button2"
android:layout_below="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:textColor="#000000"
android:id="#+id/button3"
android:layout_below="#+id/button2"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button4"
android:textColor="#000000"
android:layout_below="#+id/button3"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
Java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView xcordview = (TextView) findViewById(R.id.textView4);
final TextView ycordview = (TextView) findViewById(R.id.textView3);
RelativeLayout touchview = (RelativeLayout) findViewById(R.id.relativelayout);
touchview.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
xcordview.setText(String.valueOf(event.getX()));
ycordview.setText(String.valueOf(event.getY()));
return true;
}
});
}
}
Thank you all very very much!
Update:
public class MainActivity extends Activity {
RelativeLayout touchview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView xcordview = (TextView) findViewById(R.id.textView4);
final TextView ycordview = (TextView) findViewById(R.id.textView3);
touchview = (RelativeLayout) findViewById(R.id.relativelayout);
touchview.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
xcordview.setText(String.valueOf(event.getX()));
ycordview.setText(String.valueOf(event.getY()));
for(int i = 0; i < touchview.getChildCount(); i++){
if(checkInterSection(touchview.getChildAt(i), event.getRawX(), event.getRawY())){
Button button = (Button) findViewById(R.id.button);
button.setBackgroundColor(Color.BLUE);
break;
}
}
return true;
}
});
}
private boolean checkInterSection(View view, float rawX, float rawY) {
int[] location = new int[2];
view.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
int width = view.getWidth();
int height = view.getHeight();
//Check the intersection of point with rectangle achieved
return (!(rawX < x || rawY > x + width || rawY < y || rawY > y + height));
}
}
package com.example.touch;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
Button b1, b2, b3, b4;
int b1x1, b1x2, b1y1, b1y2;
private TextView xcordview;
private TextView ycordview;
private TextView buttonIndicator;
private RelativeLayout touchview;
private static int defaultStates[];
private Button mLastButton;
private final static int[] STATE_PRESSED = {
android.R.attr.state_pressed,
android.R.attr.state_focused
| android.R.attr.state_enabled };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xcordview = (TextView) findViewById(R.id.textView4);
ycordview = (TextView) findViewById(R.id.textView3);
buttonIndicator = (TextView) findViewById(R.id.button_indicator);
touchview = (RelativeLayout) findViewById(R.id.relativelayout);
b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
b3 = (Button) findViewById(R.id.button3);
b4 = (Button) findViewById(R.id.button4);
defaultStates = b1.getBackground().getState();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
touchview.setOnTouchListener(new View.OnTouchListener() {
private boolean isInside = false;
#Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
xcordview.setText(String.valueOf(x));
ycordview.setText(String.valueOf(y));
for (int i = 0; i < touchview.getChildCount(); i++) {
View current = touchview.getChildAt(i);
if (current instanceof Button) {
Button b = (Button) current;
if (!isPointWithin(x, y, b.getLeft(), b.getRight(), b.getTop(),
b.getBottom())) {
b.getBackground().setState(defaultStates);
}
if (isPointWithin(x, y, b.getLeft(), b.getRight(), b.getTop(),
b.getBottom())) {
b.getBackground().setState(STATE_PRESSED);
if (b != mLastButton) {
mLastButton = b;
buttonIndicator.setText(mLastButton.getText());
}
}
}
}
return true;
}
});
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
}
static boolean isPointWithin(int x, int y, int x1, int x2, int y1, int y2) {
return (x <= x2 && x >= x1 && y <= y2 && y >= y1);
}
}
layout file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:text="Y Cord : "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:text="X Cord : "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_toRightOf="#+id/textView"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView"
android:layout_marginBottom="10dp"
android:layout_toRightOf="#+id/textView"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="B1"
android:textColor="#000000" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/button1"
android:text="B2"
android:textColor="#000000" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/button2"
android:text="B3"
android:textColor="#000000" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/button3"
android:text="B4"
android:textColor="#000000" />
<TextView
android:id="#+id/button_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView4"
android:layout_marginRight="33dp"
android:text="No one"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button_indicator"
android:layout_alignBottom="#+id/button_indicator"
android:layout_marginRight="29dp"
android:layout_toLeftOf="#+id/button_indicator"
android:text="Entered: "
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
private boolean checkInterSection(View view, int rawX, int raxY) {
int[] location = new int[2];
view.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
int width = view.getWidth();
int height = view.getHeight();
//Check the intersection of point with rectangle achieved
return (!(rawX < x || rawY > x + width || rawY < y || rawY > y + height));
}
for(int i = 0; i < touchview.getChildCount(); i++){
if(checkInterSection(touchview.getChildAt(i), event.getRawX(), event.getRawY())){
if(checkInterSection(touchview.getChildAt(i), event.getRawX(), event.getRawY())){
((Button)touchview.getChildAt(i)).setBackgroundColor(Color.BLUE);// Type casting may not be required
}else{
((Button)touchview.getChildAt(i)).setBackgroundColor(Color.WHITE);
}
break;
}
}
getX() getY() for a OnTouchListener give coordinates relative the the cooresponding view.
If you prefer screen coordinates instead you can use one of the following
overwrite onTouchEvent for the activity and remove OnTouchListener-s for buttons,
in which case MotionEvent will report screen coordinates instead of Button coordinates
#Override
public boolean onTouchEvent (MotionEvent event) {
xcordview.setText(String.valueOf(event.getX()));
ycordview.setText(String.valueOf(event.getY()));
return true;
}
use getTop() getLeft() in OnTouchListener for a button:
touchview.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
xcordview.setText(String.valueOf(event.getX()+v.getLeft()));
ycordview.setText(String.valueOf(event.getY()+v.getTop()));
return true;
}
});
You may consider using GestureDetector to detect swipes, however it isn't really necessary.
karioki 's solution works well. In order to make it work even when we start the move from inside one of the buttons, just add
android:clickable="false"
for every button in xml.