Hey, I'm MakyOnCover and please sorry my English!
I'm trying to make a Android Game in java, but I'm having problems with some kind of joystick I'm trying to denvelop!
The situation is this: the bitmap named joystick1 is not creating when I pressed the screen, so I would like to know why and how can I resolve this problem?
Thank you for your attention!
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
public class Class1 extends Activity implements OnTouchListener{
/** Called when the activity is first created. */
GameView a;
boolean toque;
float x, y, jposx, jposy;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
a = new GameView(this);
a.setOnTouchListener(this);
setContentView(new GameView(this));
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
x = event.getX();
y = event.getY();
return false;
}
public class GameView extends SurfaceView implements Runnable{
private Bitmap joystick1,joystick2;
private Bitmap shot = BitmapFactory.decodeResource(getResources(),R.drawable.shot);
Class1 e;
SurfaceHolder a;
Thread thread1 = null;
boolean correr = true;
public GameView(Context context){
super (context);
a = getHolder();
thread1 = new Thread(this);
thread1.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
while(correr){
if(!a.getSurface().isValid())
continue;
Canvas canvas = a.lockCanvas();
joystick2 = BitmapFactory.decodeResource(getResources(),R.drawable.joystick2);
canvas.drawBitmap(joystick2,16,16,null);
if (x != 0 && y != 0){
joystick1 = BitmapFactory.decodeResource(getResources(),R.drawable.joystick1);
canvas.drawBitmap(joystick1,x,y,null);
}
canvas.drawBitmap(shot,0 + 20,canvas.getHeight() - shot.getHeight() - 18,null);
a.unlockCanvasAndPost(canvas);
}
}
}
}
Related
Hey guys, i have a problem at ( return super.onKeyDown(keyCode, event); )
and at ( public boolean onKeyDown(int keyCode, KeyEvent event) { )
Ihave mistake like The method onKeyDown(int, KeyEvent) is undefined for the type WebViewClient . But in the example it works.So what should i do?
Code:
package com.ihlas.koleji;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView engine = (WebView) findViewById(R.id.web_engine);
engine.loadUrl("http: //m.ih laskol eji.c om");
engine.getSettings().setJavaScriptEnabled(true);
engine.setWebViewClient(new HelloWebViewClient());
}
public class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
WebView engine;
if((keyCode == KeyEvent.KEYCODE_BACK)&& engine.canGoBack()){
engine.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
}
I have done a lot of searching and I have come up with this code to try and display images that are located in a Folder on my SDCard. The folder is located at /.data/ToDo/.nomedia/ (I am trying to hide this images from the Main Android Gallery) The Code seems to run fine, i don't get any errors, but it's just not displaying the images. I was hoping someone could tell me what I am missing. Any Help would be greatly appreciated!!
Here is my GalleryActivity
Code:
import java.io.File;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
public class GalleryActivity extends Activity {
/** Called when the activity is first created. */
private Cursor imagecursor, actualimagecursor, cursor;
private int image_column_index, actual_image_column_index;
File sdCardDir = Environment.getExternalStorageDirectory(); //SDCard Location
String imagesDir = ("sdCardDir" + "/.data/ToDo/.nomedia/"); //Path to Images
GridView imagegrid;
private int count;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
init_phone_image_grid();
}
private void init_phone_image_grid() {
String[] img = { MediaStore.Images.Media._ID };
imagecursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, img, MediaStore.Images.Media.DATA + " like ? ", new String[] {imagesDir}, null);
image_column_index = imagecursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
count = imagecursor.getCount();
imagegrid = (GridView) findViewById(R.id.sdcard);
imagegrid.setAdapter(new ImageAdapter(getApplicationContext()));
imagegrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
System.gc();
String[] proj = { MediaStore.Images.Media.DATA };
actualimagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,null, null, null);
actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToPosition(position);
String i = actualimagecursor.getString(actual_image_column_index);
System.gc();
Intent intent = new Intent(getApplicationContext(), GalleryFlow.class);
intent.putExtra("filename", i);
startActivity(intent);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position,View convertView,ViewGroup parent) {
System.gc();
ImageView i = new ImageView(mContext.getApplicationContext());
if (convertView == null) {
imagecursor.moveToPosition(position);
int id = imagecursor.getInt(image_column_index);
int imageID = 0;
Uri uri = Uri.withAppendedPath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(imageID) );
String url = uri.toString();
// Set the content of the image based on the image URI
int originalImageId = Integer.parseInt(url.substring(url.lastIndexOf("/") + 1, url.length()));
Bitmap b = MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(), originalImageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
//i.setImageURI(Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(imageID)));
i.setImageBitmap(b);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
}
else {
i = (ImageView) convertView;
}
return i;
}
}
}
I've been hacking away at a few java files (PlatlogoActivity.java, Nyandroid.java) extracted from AOSP ICS source in Eclipse. There were some errors that I was able to solve (some funky ones about vibration, but I just removed all code related to vibration instead) but now there is one error, that no matter what, I can't solve. In the Nyandroid.java, I keep on getting the error "Cannot cast from TimeAnimator to ValueAnimator" on the line "((ValueAnimator) mAnim).cancel();" no matter how much I try changing that line (for example to "mAnim.cancel();") based on some custom ROM sources that I've looked through, and some stackoverflow questions. The app source is attached to this post, and below you can find the Nyandroid.java if you're willing to help - please do. I want to get into app developing for Android, or atleast understanding some java. I managed to port the Gingerbread platlogo for all Android versions but it's obviously much easier to do because it's just one still image and a toast. But I really want to port the ICS Nyandroid easter egg, for some practice with java.
/*);
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.nyandroid;
import android.animation.AnimatorSet;
import android.animation.PropertyValuesHolder;
import android.animation.ObjectAnimator;
import android.animation.TimeAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import java.util.HashMap;
import java.util.Random;
public class Nyandroid extends Activity {
final static boolean DEBUG = false;
public static class Board extends FrameLayout
{
public static final boolean FIXED_STARS = true;
public static final int NUM_CATS = 20;
static Random sRNG = new Random();
static float lerp(float a, float b, float f) {
return (b-a)*f + a;
}
static float randfrange(float a, float b) {
return lerp(a, b, sRNG.nextFloat());
}
static int randsign() {
return sRNG.nextBoolean() ? 1 : -1;
}
static <E> E pick(E[] array) {
if (array.length == 0) return null;
return array[sRNG.nextInt(array.length)];
}
public class FlyingCat extends ImageView {
public static final float VMAX = 1000.0f;
public static final float VMIN = 100.0f;
public float v, vr;
public float dist;
public float z;
public ComponentName component;
public FlyingCat(Context context, AttributeSet as) {
super(context, as);
setImageResource(R.drawable.nyandroid_anim); // @@@
if (DEBUG) setBackgroundColor(0x80FF0000);
}
public String toString() {
return String.format("<cat (%.1f, %.1f) (%d x %d)>",
getX(), getY(), getWidth(), getHeight());
}
public void reset() {
final float scale = lerp(0.1f,2f,z);
setScaleX(scale); setScaleY(scale);
setX(-scale*getWidth()+1);
setY(randfrange(0, Board.this.getHeight()-scale*getHeight()));
v = lerp(VMIN, VMAX, z);
dist = 0;
// android.util.Log.d("Nyandroid", "reset cat: " + this);
}
public void update(float dt) {
dist += v * dt;
setX(getX() + v * dt);
}
}
TimeAnimator mAnim;
public Board(Context context, AttributeSet as) {
super(context, as);
setLayerType(View.LAYER_TYPE_HARDWARE, null);
setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
setBackgroundColor(0xFF003366);
}
private void reset() {
// android.util.Log.d("Nyandroid", "board reset");
removeAllViews();
final ViewGroup.LayoutParams wrap = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
if (FIXED_STARS) {
for(int i=0; i<20; i++) {
ImageView fixedStar = new ImageView(getContext(), null);
if (DEBUG) fixedStar.setBackgroundColor(0x8000FF80);
fixedStar.setImageResource(R.drawable.star_anim); // @@@
addView(fixedStar, wrap);
final float scale = randfrange(0.1f, 1f);
fixedStar.setScaleX(scale); fixedStar.setScaleY(scale);
fixedStar.setX(randfrange(0, getWidth()));
fixedStar.setY(randfrange(0, getHeight()));
final AnimationDrawable anim = (AnimationDrawable) fixedStar.getDrawable();
postDelayed(new Runnable() {
public void run() {
anim.start();
}}, (int) randfrange(0, 1000));
}
}
for(int i=0; i<NUM_CATS; i++) {
FlyingCat nv = new FlyingCat(getContext(), null);
addView(nv, wrap);
nv.z = ((float)i/NUM_CATS);
nv.z *= nv.z;
nv.reset();
nv.setX(randfrange(0,Board.this.getWidth()));
final AnimationDrawable anim = (AnimationDrawable) nv.getDrawable();
postDelayed(new Runnable() {
public void run() {
anim.start();
}}, (int) randfrange(0, 1000));
}
if (mAnim != null) {
((ValueAnimator) mAnim).cancel();
}
mAnim = new TimeAnimator();
mAnim.setTimeListener(new TimeAnimator.TimeListener() {
public void onTimeUpdate(TimeAnimator animation, long totalTime, long deltaTime) {
// setRotation(totalTime * 0.01f); // not as cool as you would think
// android.util.Log.d("Nyandroid", "t=" + totalTime);
for (int i=0; i<getChildCount(); i++) {
View v = getChildAt(i);
if (!(v instanceof FlyingCat)) continue;
FlyingCat nv = (FlyingCat) v;
nv.update(deltaTime / 1000f);
final float catWidth = nv.getWidth() * nv.getScaleX();
final float catHeight = nv.getHeight() * nv.getScaleY();
if ( nv.getX() + catWidth < -2
|| nv.getX() > getWidth() + 2
|| nv.getY() + catHeight < -2
|| nv.getY() > getHeight() + 2)
{
nv.reset();
}
}
}
});
}
@Override
protected void onSizeChanged (int w, int h, int oldw, int oldh) {
super.onSizeChanged(w,h,oldw,oldh);
// android.util.Log.d("Nyandroid", "resized: " + w + "x" + h);
post(new Runnable() { public void run() {
reset();
mAnim.start();
} });
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mAnim.cancel();
}
@Override
public boolean isOpaque() {
return true;
}
}
private Board mBoard;
@Override
public void onStart() {
super.onStart();
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
);
}
@Override
public void onResume() {
super.onResume();
mBoard = new Board(this, null);
setContentView(mBoard);
mBoard.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int vis) {
if (0 == (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION)) {
Nyandroid.this.finish();
}
}
});
}
@Override
public void onUserInteraction() {
// android.util.Log.d("Nyandroid", "finishing on user interaction");
finish();
}
}
Click to expand...
Click to collapse
I made Instagram type application in Android Studio, but whenever I try to upload image in my app, it uploads to my profile picture. I checked my intents and they are really perfect. First file is GalleryFragment.java in which we will select the photo which we want to upload and Second file is NextActivity.java which is used to Share the image to profile. But in GalleryFragment.java I have intent getActivity() to NextActivity.java and AccountSettingsActivity.java in which we can change out profile picture. But whenever I click on Next it doesn't take me to NextActivity.java but to the AccountSettingsActivity.java and updates my profile picture. If there is Firebase error so tell me. And the same issue is occurred when I try to upload photo from camera inside the application and it doesn't do anything. I have posted 3 files.
GalleryFragment.java
Code:
package darthvader.com.pictagram.Share;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import java.util.ArrayList;
import java.util.Objects;
import darthvader.com.pictagram.Profile.AccountSettingsActivity;
import darthvader.com.pictagram.R;
import darthvader.com.pictagram.Utils.FilePaths;
import darthvader.com.pictagram.Utils.FileSearch;
import darthvader.com.pictagram.Utils.GridImageAdapter;
public class GalleryFragment extends Fragment {
private static final String TAG = "GalleryFragment";
//constants
private static final int NUM_GRID_COLUMNS = 3;
//widgets
private GridView gridView;
private ImageView galleryImage;
private ProgressBar mProgressBar;
private Spinner directorySpinner;
//vars
private ArrayList<String> directories;
private String mAppend = "file:/";
private String mSelectedImage;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
galleryImage = view.findViewById(R.id.galleryImageView);
gridView = view.findViewById(R.id.gridView);
directorySpinner = view.findViewById(R.id.spinnerDirectory);
mProgressBar = view.findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
directories = new ArrayList<>();
Log.d(TAG, "onCreateView: started.");
ImageView shareClose = view.findViewById(R.id.ivCloseShare);
shareClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: closing the gallery fragment.");
Objects.requireNonNull(getActivity()).finish();
}
});
TextView nextScreen = view.findViewById(R.id.tvNext);
nextScreen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to the final share screen.");
if(isRootTask()){
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
startActivity(intent);
}else{
Intent intent = new Intent(getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
startActivity(intent);
getActivity().finish();
}
}
});
init();
return view;
}
private boolean isRootTask(){
return ((ShareActivity) getActivity()).getTask() == 0;
}
private void init(){
FilePaths filePaths = new FilePaths();
//check for other folders indide "/storage/emulated/0/pictures"
if (FileSearch.getDirectoryPaths(filePaths.PICTURES) != null) {
directories = FileSearch.getDirectoryPaths(filePaths.PICTURES);
}
directories.add(filePaths.CAMERA);
ArrayList<String> directoryNames = new ArrayList<>();
for (int i = 0; i < directories.size(); i++) {
Log.d(TAG, "init: directory: " + directories.get(i));
int index = directories.get(i).lastIndexOf("/");
String string = directories.get(i).substring(index);
directoryNames.add(string);
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(Objects.requireNonNull(getActivity()),
android.R.layout.simple_spinner_item, directoryNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
directorySpinner.setAdapter(adapter);
directorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected: " + directories.get(position));
//setup our image grid for the directory chosen
setupGridView(directories.get(position));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void setupGridView(String selectedDirectory){
Log.d(TAG, "setupGridView: directory chosen: " + selectedDirectory);
final ArrayList<String> imgURLs = FileSearch.getFilePaths(selectedDirectory);
//set the grid column width
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth/NUM_GRID_COLUMNS;
gridView.setColumnWidth(imageWidth);
//use the grid adapter to adapter the images to gridview
GridImageAdapter adapter = new GridImageAdapter(getActivity(), R.layout.layout_grid_imageview, mAppend, imgURLs);
gridView.setAdapter(adapter);
//set the first image to be displayed when the activity fragment view is inflated
try{
setImage(imgURLs.get(0), galleryImage, mAppend);
mSelectedImage = imgURLs.get(0);
}catch (ArrayIndexOutOfBoundsException e){
Log.e(TAG, "setupGridView: ArrayIndexOutOfBoundsException: " +e.getMessage() );
}
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected an image: " + imgURLs.get(position));
setImage(imgURLs.get(position), galleryImage, mAppend);
mSelectedImage = imgURLs.get(position);
}
});
}
private void setImage(String imgURL, ImageView image, String append){
Log.d(TAG, "setImage: setting image");
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(append + imgURL, image, new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
mProgressBar.setVisibility(View.VISIBLE);
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
mProgressBar.setVisibility(View.INVISIBLE);
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
mProgressBar.setVisibility(View.INVISIBLE);
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
mProgressBar.setVisibility(View.INVISIBLE);
}
});
}
}
NextActivity.java
Code:
package darthvader.com.pictagram.Share;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import darthvader.com.pictagram.R;
import darthvader.com.pictagram.Utils.FirebaseMethods;
import darthvader.com.pictagram.Utils.UniversalImageLoader;
import darthvader.com.pictagram.models.User;
public class NextActivity extends AppCompatActivity {
private static final String TAG = "NextActivity";
//firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private FirebaseMethods mFirebaseMethods;
//widgets
private EditText mCaption;
//vars
private String mAppend = "file:/";
private int imageCount = 0;
private String imgUrl;
private Bitmap bitmap;
private Intent intent;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
mFirebaseMethods = new FirebaseMethods(NextActivity.this);
mCaption = findViewById(R.id.caption);
setupFirebaseAuth();
ImageView backArrow = findViewById(R.id.ivBackArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: closing the activity");
finish();
}
});
TextView share = findViewById(R.id.tvShare);
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to the final share screen.");
//upload the image to firebase
Toast.makeText(NextActivity.this, "Attempting to upload new photo", Toast.LENGTH_SHORT).show();
String caption = mCaption.getText().toString();
if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, imgUrl,null);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = intent.getParcelableExtra(getString(R.string.selected_bitmap));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, null,bitmap);
}
}
});
setImage();
}
private void someMethod(){
/*
Step 1)
Create a data model for Photos
Step 2)
Add properties to the Photo Objects (caption, date, imageUrl, photo_id, tags, user_id)
Step 3)
Count the number of photos that the user already has.
Step 4)
a) Upload the photo to Firebase Storage
b) insert into 'photos' node
c) insert into 'user_photos' node
*/
}
/**
* gets the image url from the incoming intent and displays the chosen image
*/
private void setImage(){
intent = getIntent();
ImageView image = findViewById(R.id.imageShare);
if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
Log.d(TAG, "setImage: got new image url: " + imgUrl);
UniversalImageLoader.setImage(imgUrl, image, null, mAppend);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = intent.getParcelableExtra(getString(R.string.selected_bitmap));
Log.d(TAG, "setImage: got new bitmap");
image.setImageBitmap(bitmap);
}
}
/*
------------------------------------ Firebase ---------------------------------------------
*/
/**
* Setup the firebase auth object
*/
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
Log.d(TAG, "onDataChange: image count: " + imageCount);
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
imageCount = mFirebaseMethods.getImageCount(dataSnapshot);
Log.d(TAG, "onDataChange: image count: " + imageCount);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
PhotoFragment.java
Code:
package darthvader.com.pictagram.Share;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import java.util.Objects;
import darthvader.com.pictagram.Profile.AccountSettingsActivity;
import darthvader.com.pictagram.R;
import darthvader.com.pictagram.Utils.Permissions;
public class PhotoFragment extends Fragment {
private static final String TAG = "PhotoFragment";
//constant
private static final int PHOTO_FRAGMENT_NUM = 1;
private static final int GALLERY_FRAGMENT_NUM = 2;
private static final int CAMERA_REQUEST_CODE = 5;
@Nullable
@Override
public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_photo, container, false);
Log.d(TAG, "onCreateView: started.");
Button btnLaunchCamera = (Button) view.findViewById(R.id.btnLaunchCamera);
btnLaunchCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: launching camera.");
if(((ShareActivity)getActivity()).getCurrentTabNumber() == PHOTO_FRAGMENT_NUM){
if(((ShareActivity)getActivity()).checkPermissions(Permissions.CAMERA_PERMISSION[0])){
Log.d(TAG, "onClick: starting camera");
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
}else{
Intent intent = new Intent(getActivity(), ShareActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
}
});
return view;
}
private boolean isRootTask(){
if(((ShareActivity)getActivity()).getTask() == 0){
return true;
}
else{
return false;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE){
Log.d(TAG, "onActivityResult: done taking a photo.");
Log.d(TAG, "onActivityResult: attempting to navigate to final share screen.");
Bitmap bitmap;
bitmap = (Bitmap) Objects.requireNonNull(data.getExtras()).get("data");
if(isRootTask()){
try{
Log.d(TAG, "onActivityResult: received new bitmap from camera: " + bitmap);
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.selected_bitmap), bitmap);
startActivity(intent);
}catch (NullPointerException e){
Log.d(TAG, "onActivityResult: NullPointerException: " + e.getMessage());
}
}else{
try{
Log.d(TAG, "onActivityResult: received new bitmap from camera: " + bitmap);
Intent intent = new Intent(getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_bitmap), bitmap);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
startActivity(intent);
getActivity().finish();
}catch (NullPointerException e){
Log.d(TAG, "onActivityResult: NullPointerException: " + e.getMessage());
}
}
}
}
}
In the following code drawing using DrawView works for me. But I want to draw a shape on touching the canvas. MyView is supposed to do that, but how to get it working?
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class MainActivity extends Activity {
DrawView drawView;
MyView myView;
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
drawView.setBackgroundColor(Color.WHITE);
setContentView(drawView);
myView = new MyView(this);
myView.setBackgroundColor(Color.WHITE);
setContentView(drawView);
}
class DrawView extends View {
Paint paint = new Paint();
public DrawView(Context context) {
super(context);
paint.setColor(Color.BLACK);
}
@override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(10, 20, 30, 40, paint);
canvas.drawLine(20, 10, 50, 20, paint);
}
}
class MyView extends View {
private float xDown = 0,yDown = 0, xUp = 0, yUp = 0;
Paint mPaint;
boolean touched = false;
public MyView(Context context) {
super(context);
init(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
mPaint = new Paint();
mPaint.setColor(Color.BLUE);
mPaint.setStyle(Paint.Style.STROKE);
}
@override
protected void onDraw (Canvas canvas) {
canvas.drawColor(Color.TRANSPARENT);
if(touched) {
canvas.drawRect(xDown, yDown, xUp, yUp, mPaint);
}
}
@override
public boolean onTouchEvent (MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
xDown = event.getX();
yDown = event.getY();
xUp = 0;
yUp = 0;
break;
case MotionEvent.ACTION_MOVE:
xUp = event.getX();
yUp = event.getY();
touched = true;
break;
case MotionEvent.ACTION_UP:
xUp = event.getX();
yUp = event.getY();
touched = true;
break;
}
invalidate();
return true;
}
}
}
The second
BjornAndroid said:
setContentView(drawView);
Click to expand...
Click to collapse
had to be
setContentView(myView);