I have an app in which many activities open another in which some things are set after the buttons that opened it(images, tags, etc.).After this activity is closed I want to be returned a string vith value "1" which will be converted to an int and used to set a score.
In activity that returns i have this:
Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.vie);
img = (ImageView) findViewById(R.id.img);
et = (EditText) findViewById(R.id.et);
btn = (Button) findViewById(R.id.btnCheck);
txt = (TextView) findViewById(R.id.txt);
win_sound = MediaPlayer.create(Vie.this, R.raw.win);
wrong_sound= MediaPlayer.create(Vie.this, R.raw.wrong);
i = getIntent();
Bitmap back = i.getParcelableExtra("back");
Drawable b = new BitmapDrawable(getResources(), back);
img.setImageDrawable(b);
String tag = i.getStringExtra("tag");
Object tag2 = (Object) tag;
img.setTag(tag2);
btn.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
boolean mb = check(et, img);
if (mb) {
// Sunet toast thread
txt.setText(title(img));
win_sound.start();
i.putExtra("score", "1");
setResult(RESULT_OK, i);
Thread t = new Thread() {
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
sleep(win_sound.getDuration());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
finish();
}
}
};
t.start();
}
if (!mb) {
// sunet toast thread
wrong_sound.start();
Toast t = Toast.makeText(getApplicationContext(),"Wrong answer! Please check if you have spelled corectly the name of the team!",Toast.LENGTH_LONG);
t.show();
}
}
And the OnActivityResult methode:
int a = 0
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (data.getExtras().containsKey("score")) {
a +=Integer.valueOf(data.getStringExtra("score"));
}
}
and a textView is set to show a:
txtScore.setText(a);
But this gives me an error, this is my LogCat:
06-29 15:28:25.312: E/AndroidRuntime(981): Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
06-29 15:28:25.312: E/AndroidRuntime(981): at android.content.res.Resources.getText(Resources.java:230)
06-29 15:28:25.312: E/AndroidRuntime(981): at android.widget.TextView.setText(TextView.java:3769)
06-29 15:28:25.312: E/AndroidRuntime(981): at com.RandDdev.uclquiz.Teams.onCreate(Teams.java:61)
Could you help me?
txtScore.setText(a);
a is a Integer. So Android is looking for a String inside R with that id.
change with
txtScore.setText(String.valueOf(a));
you are using setText(int), instead of setText(Charsequence)
You should use the below
txtScore.setText(String.valueOf(a));
public final void setText (int resid)
http://developer.android.com/reference/android/widget/TextView.html
So it will look for a resource id which is an int value. This does not exist. Hence you get Resource not found exception
Please try txtScore.setText(""+a);
You cannot set an int directly to TextView
Related
I have an app that opens up a file picker and it outputs the path of that file in a Toast Message.
But I would like to change it such that the file that I pick is passed as a parameter to a function.
My activity looks like this:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.btn_picker);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 7);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case 7:
if (resultCode == RESULT_OK) {
String PathHolder = data.getData().getPath();
Toast.makeText(MainActivity.this, "The Files path is: "+ PathHolder, Toast.LENGTH_LONG).show();
}
break;
}
}
}
And it does what it is supposed to do but instead of outputting the file path, I would like to call the function
importToFile()
From the manage class.
I would like to do something like this:
manage.importToFile(File1)
Where File1 is the file I selected from the file picker.
How can I do that.
Thanks in advance.
You can use File class in android to work with files. Create an instance of File using the path of the selected file and pass it to that method of yours. Something like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case 7:
if (resultCode == RESULT_OK) {
// as #Taseer Ahmad said its not a good way to get path of the file.
//String PathHolder = data.getData().getPath();
String PathHolder = getPath(this, data.getData());
if (!TextUtils.isEmpty(PathHolder)) {
File file = new File(PathHolder);
manager.importToFile(file);
Toast.makeText(MainActivity.this, "The Files path is: "+ PathHolder, Toast.LENGTH_LONG).show();
}
}
break;
}
}
EDIT
As #Taseer Ahmad said, data.getData().getPath() is not a safe way to get path of the selected file. This code is copied from here.
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
I have been trying to learn java so I can program for android. I have made an app that has 2 classes, Match and MatchResult. In Match you can push a button and it will add one to a counter. At the bottom of the page i have a button that will bring you to the next class and display the counter in a textview. Im trying to send the info trough a getIntent but its something wrong that I cant find. Here is the code:
Match:
public class Match extends Activity implements OnClickListener {
public final static String EXTRA_MESSAGE_HOME = "com.epstudios.basketballmanager_v1.MATCHRESULT";
public final static String EXTRA_MESSAGE_AWAY = "com.epstudios.basketballmanager_v1.MATCHRESULT";
TextView awayGoals, homeGoals, home, away;
Button homebtn, awaybtn, gotoresult;
int homecount, awaycount;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match);
baconAndEggs();
homebtn.setOnClickListener(this);
awaybtn.setOnClickListener(this);
gotoresult.setOnClickListener(this);
}
public void sendInfo(View view) {
Intent intent = new Intent(this, MatchResult.class);
intent.putExtra(EXTRA_MESSAGE_AWAY, awaycount);
intent.putExtra(EXTRA_MESSAGE_HOME, homecount);
startActivity(intent);
}
private void baconAndEggs() {
awayGoals = (TextView) findViewById(R.id.Away);
homeGoals = (TextView) findViewById(R.id.Home);
homebtn = (Button) findViewById(R.id.homeBtn);
awaybtn = (Button) findViewById(R.id.awayBtn);
gotoresult = (Button) findViewById(R.id.matchResult);
}
public void counter() {
awaycount = 1;
homecount = 0;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.homeBtn:
homecount++;
homeGoals.setText("Lakers: " + homecount);
break;
case R.id.awayBtn:
awaycount++;
awayGoals.setText("Heat: " + awaycount);
break;
case R.id.matchResult:
Intent result = new Intent(this, MatchResult.class);
startActivity(result);
break;
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
MatchResult:
public class MatchResult extends Activity {
TextView home, away;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match_result);
resultcounter();
int awayresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_AWAY, -1);
int homeresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_HOME, -1);
home.setText(String.valueOf(homeresult));
Log.d("Petter", String.valueOf(homeresult));
away.setText(String.valueOf(awayresult));
}
public void resultcounter() {
// TODO Auto-generated method stub
home = (TextView) findViewById(R.id.homeresult);
away = (TextView) findViewById(R.id.awayresult);
}
}
Hmm, why not try scrapping your sendInfo() function and adding this line under your result intent instead:
result.putExtra(Match.EXTRA_MESSAGE_AWAY, awayCount);
It should work now.
It seems that code having 2 ways to call MatchResult activity hence try to use :
hasExtra() method to check whether that extra is passed with the Intent.
The constructor of Intent should have the context of your class. But in your case this refers View.OnClickListener()! So, just change it as in below.
...
case R.id.matchResult:
Intent result = new Intent(Match.this, MatchResult.class); // Like here
result.putExtra(EXTRA_MESSAGE_AWAY, awaycount);
result.putExtra(EXTRA_MESSAGE_HOME, homecount);
startActivity(result);
break;
}
...
Edit: You have never used sendInfo method. As far as I get, you could remove your sendInfo method and put those codes into switch case.
I would be create a static variable shared between activities.
I am new to java programming and im currently trying to pass over info to another class and display it as a TextView. I have two classes: Match and MatchResult. In Match you can push a button and a int will +1. I also have a button on the site which can make you go to the next class. In the next class i want do make the score get displayed in a TextView. But something isn't working and I don't understand why. Here is my code hope someone can help me:
Match.java:
public class Match extends Activity implements OnClickListener{
public final static String EXTRA_MESSAGE = "com.epstudios.basketballmanager_v1.MATCHRESULT";
TextView awayGoals, homeGoals, home, away;
Button homebtn, awaybtn, gotoresult;
int homecount, awaycount;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match);
baconAndEggs();
homebtn.setOnClickListener(this);
awaybtn.setOnClickListener(this);
gotoresult.setOnClickListener(this);
}
public void sendInfo(View view) {
Intent intent = new Intent(this, Match.class);
intent.putExtra(EXTRA_MESSAGE, awaycount);
Intent homeintent = new Intent(this, Match.class);
homeintent.putExtra(EXTRA_MESSAGE, homecount);
}
private void baconAndEggs() {
awayGoals = (TextView) findViewById(R.id.Away);
homeGoals = (TextView) findViewById(R.id.Home);
homebtn = (Button) findViewById(R.id.homeBtn);
awaybtn = (Button) findViewById(R.id.awayBtn);
gotoresult = (Button) findViewById(R.id.matchResult);
}
public void counter() {
awaycount = 1;
homecount = 0;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.homeBtn:
homecount ++;
homeGoals.setText("Lakers: " + homecount);
break;
case R.id.awayBtn:
awaycount ++;
awayGoals.setText("Heat: " + awaycount);
break;
case R.id.matchResult:
Intent result = new Intent(this, MatchResult.class);
startActivity(result);
break;
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
MatchResult.java:
public class MatchResult extends Activity {
TextView home, away;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match_result);
resultcounter();
Intent awayintent = getIntent();
String awayresult = awayintent.getStringExtra(Match.EXTRA_MESSAGE);
Intent homeintent = getIntent();
String homeresult = homeintent.getStringExtra(Match.EXTRA_MESSAGE);
home.setText(homeresult);
Log.d("Petter", homeresult);
}
The Log dosen't work
You're adding as 'Integer' putExtra("KEY", int) and retrieving as 'String' (getStringExtra)
Change sendInfo with:
public void sendInfo(View view) {
Intent intent = new Intent(this, MatchResult.class);
intent.putExtra(EXTRA_MESSAGE_AWAY, awaycount);
intent.putExtra(EXTRA_MESSAGE_HOME, homecount);
startActivituy(intent);
}
Change MatchResult with:
public class MatchResult extends Activity {
TextView home, away;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match_result);
resultcounter();
int awayresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_AWAY, -1);
int homeresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_HOME, -1);
home.setText(String.valueOf(homeresult));
Log.d("Petter", String.valueOf(homeresult));
}
You are starting the second Activity using this:
case R.id.matchResult:
Intent result = new Intent(this, MatchResult.class);
result.putExtra(EXTRA_MESSAGE_HOME, awaycount);//Use this
result.putExtra(EXTRA_MESSAGE_AWAY, homecount);//Use this
startActivity(result);
break;
put an Intent here. Don't use 2 intents. Just put the two variables using 2 keys in same intent.
In second activity do this:
Intent intent = getIntent();
String awayresult = String.valueOf(intent.getIntExtra(Match.EXTRA_MESSAGE_AWAY, -1));
String homeresult = String.valueOf(intent.getIntExtra(Match.EXTRA_MESSAGE_HOME, -1));
Match:
public class Match extends Activity implements OnClickListener {
public final static String EXTRA_MESSAGE_HOME = "com.epstudios.basketballmanager_v1.MATCHRESULT";
public final static String EXTRA_MESSAGE_AWAY = "com.epstudios.basketballmanager_v1.MATCHRESULT";
TextView awayGoals, homeGoals, home, away;
Button homebtn, awaybtn, gotoresult;
int homecount, awaycount;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match);
baconAndEggs();
homebtn.setOnClickListener(this);
awaybtn.setOnClickListener(this);
gotoresult.setOnClickListener(this);
}
public void sendInfo(View view) {
Intent intent = new Intent(this, MatchResult.class);
intent.putExtra(EXTRA_MESSAGE_AWAY, awaycount);
intent.putExtra(EXTRA_MESSAGE_HOME, homecount);
startActivity(intent);
}
private void baconAndEggs() {
awayGoals = (TextView) findViewById(R.id.Away);
homeGoals = (TextView) findViewById(R.id.Home);
homebtn = (Button) findViewById(R.id.homeBtn);
awaybtn = (Button) findViewById(R.id.awayBtn);
gotoresult = (Button) findViewById(R.id.matchResult);
}
public void counter() {
awaycount = 1;
homecount = 0;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.homeBtn:
homecount++;
homeGoals.setText("Lakers: " + homecount);
break;
case R.id.awayBtn:
awaycount++;
awayGoals.setText("Heat: " + awaycount);
break;
case R.id.matchResult:
Intent result = new Intent(this, MatchResult.class);
startActivity(result);
break;
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
MatchResult:
public class MatchResult extends Activity {
TextView home, away;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match_result);
resultcounter();
int awayresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_AWAY, -1);
int homeresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_HOME, -1);
home.setText(String.valueOf(homeresult));
Log.d("Petter", String.valueOf(homeresult));
away.setText(String.valueOf(awayresult));
}
public void resultcounter() {
// TODO Auto-generated method stub
home = (TextView) findViewById(R.id.homeresult);
away = (TextView) findViewById(R.id.awayresult);
}
}
I have successfully been able to store user entered information into parse, but I haven't figure out how to do store a user uploaded image that would be associated with the current user in parse, and to retrieve a user image at a later time.
To clarify this, below is the code I have used for my profile creation activity, an activity that is prompted after the user has signing using social media and responds to a series of questions like age, preferred name, and where those information are later updated in the parse database and added to the current user.
Also in the activity, the user is already able to upload a picture from their device, my issue now resolves around taking that uploaded picture and storing it on parse, and associating the image with the current user who has signing using their social media account - the social media integration is done through parse.
I have looked into the following guide, but is still greatly confused.
https://www.parse.com/docs/android_guide#files
Any assistance would be greatly appreciated.
Thanks in advance.
public class ProfileCreation extends Activity {
private static final int RESULT_LOAD_IMAGE = 1;
FrameLayout layout;
Button save;
protected EditText mName;
protected EditText mAge;
protected EditText mHeadline;
protected Button mConfirm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_creation);
Parse.initialize(this, "ID", "ID");
mName = (EditText)findViewById(R.id.etxtname);
mAge = (EditText)findViewById(R.id.etxtage);
mHeadline = (EditText)findViewById(R.id.etxtheadline);
mConfirm = (Button)findViewById(R.id.btnConfirm);
mConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = mName.getText().toString();
String age = mAge.getText().toString();
String headline = mHeadline.getText().toString();
age = age.trim();
name = name.trim();
headline = headline.trim();
if (age.isEmpty() || name.isEmpty() || headline.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(R.string.signup_error_message)
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else {
// create the new user!
setProgressBarIndeterminateVisibility(true);
ParseUser currentUser = ParseUser.getCurrentUser();
currentUser.put("name", name);
currentUser.put("age", age);
currentUser.put("headline", headline);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success!
Intent intent = new Intent(ProfileCreation.this, MoodActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
save = (Button) findViewById(R.id.button2);
String picturePath = PreferenceManager.getDefaultSharedPreferences(this).getString("picturePath", "");
if (!picturePath.equals("")) {
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
SeekBar seekBar = (SeekBar) findViewById(R.id.seekBarDistance);
final TextView seekBarValue = (TextView) findViewById(R.id.seekBarDistanceValue);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
seekBarValue.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
SeekBar seekBarMinimum = (SeekBar) findViewById(R.id.seekBarMinimumAge);
final TextView txtMinimum = (TextView) findViewById(R.id.tMinAge);
seekBarMinimum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMinimum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
SeekBar seekBarMaximum = (SeekBar) findViewById(R.id.seekBarMaximumAge);
final TextView txtMaximum = (TextView) findViewById(R.id.tMaxAge);
seekBarMaximum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMaximum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Locate the image in res >
Bitmap bitmap = BitmapFactory.decodeFile("picturePath");
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
Object image = null;
try {
String path = null;
image = readInFile(path);
} catch (Exception e) {
e.printStackTrace();
}
// Create the ParseFile
ParseFile file = new ParseFile("picturePath", (byte[]) image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a New Class called "ImageUpload" in Parse
ParseObject imgupload = new ParseObject("Image");
// Create a column named "ImageName" and set the string
imgupload.put("Image", "picturePath");
// Create a column named "ImageFile" and insert the image
imgupload.put("ImageFile", file);
// Create the class and the columns
imgupload.saveInBackground();
// Show a simple toast message
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
private byte[] readInFile(String path) throws IOException {
// TODO Auto-generated method stub
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
}
Also in the activity, the user is already able to upload a picture
from their device, my issue now resolves around taking that uploaded
picture and storing it on parse, and associating the image with the
current user who has signing using their social media account - the
social media integration is done through parse.
Read the docs on files and on the response type when a file is upload to parse.com
"media":{"__type":"File","name":"e580f231-...-picf1","url":"http://files.parse.com/..52d6-picf1"}
So, after POST on the file to parse, you have a logical FILE entity that you can then point to in another class.
In that other clase , you can also point to the user who created the FILE.
Class2 {"createdby" : pointer($user), "media" : pointer($file)}
With that, you have a separate class with 2 , pointer types ( toUser, toFile ) and the col headers on the data browser will show :
pointer<_User> for the user
file for the file
I have successfully been able to store user entered information into parse, but I have been having difficulty storing images into to parse, to be able to retrieve at a later date.
To clarify this, below is the code I have used for my profile creation activity, an activity that is prompted after the user has signing using social media and responds to a series of questions like age, preferred name, and where those information are later updated in the parse database and added to the current user.
Also in the activity, the user is already able to upload a picture from their device, my issue now resolves around taking that uploaded picture and storing it on parse, and associating the image with the current user who has signing using their social media account - the social media integration is done through parse.
I have looked into the following guide, but is still greatly confused.https://www.parse.com/docs/android_guide#files
Now I have tried to accomplish this, and have left my comments in the code below.
Any assistance would be greatly appreciated. Thanks in advance.
public class ProfileCreation extends Activity {
private static final int RESULT_LOAD_IMAGE = 1;
FrameLayout layout;
Button save;
protected EditText mName;
protected EditText mAge;
protected EditText mHeadline;
protected ImageView mprofilePicture;
protected Button mConfirm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_creation);
RelativeLayout v = (RelativeLayout) findViewById(R.id.main);
v.requestFocus();
Parse.initialize(this, "ID", "ID");
mName = (EditText)findViewById(R.id.etxtname);
mAge = (EditText)findViewById(R.id.etxtage);
mHeadline = (EditText)findViewById(R.id.etxtheadline);
mprofilePicture = (ImageView)findViewById(R.id.profilePicturePreview);
mConfirm = (Button)findViewById(R.id.btnConfirm);
mConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = mName.getText().toString();
String age = mAge.getText().toString();
String headline = mHeadline.getText().toString();
age = age.trim();
name = name.trim();
headline = headline.trim();
if (age.isEmpty() || name.isEmpty() || headline.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(R.string.signup_error_message)
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else {
// create the new user!
setProgressBarIndeterminateVisibility(true);
ParseUser currentUser = ParseUser.getCurrentUser();
/* This is the section where the images is converted, saved, and uploaded. I have not been able Locate the image from the ImageView, where the user uploads the picture to imageview from either their gallery and later on from facebook */
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
/*fron image view */);
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image = stream.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile("profilePicture.png", image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a column named "ImageName" and set the string
currentUser.put("ImageName", "AndroidBegin Logo");
// Create a column named "ImageFile" and insert the image
currentUser.put("ProfilePicture", file);
// Create the class and the columns
currentUser.saveInBackground();
currentUser.put("name", name);
currentUser.put("age", age);
currentUser.put("headline", headline);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success!
Intent intent = new Intent(ProfileCreation.this, MoodActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
SeekBar seekBar = (SeekBar) findViewById(R.id.seekBarDistance);
final TextView seekBarValue = (TextView) findViewById(R.id.seekBarDistanceValue);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
seekBarValue.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
Button mcancel = (Button)findViewById(R.id.btnBack);
mcancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProfileCreation.this.startActivity(new Intent(ProfileCreation.this, LoginActivity.class));
}
});
SeekBar seekBarMinimum = (SeekBar) findViewById(R.id.seekBarMinimumAge);
final TextView txtMinimum = (TextView) findViewById(R.id.tMinAge);
seekBarMinimum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMinimum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
SeekBar seekBarMaximum = (SeekBar) findViewById(R.id.seekBarMaximumAge);
final TextView txtMaximum = (TextView) findViewById(R.id.tMaxAge);
seekBarMaximum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMaximum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
private byte[] readInFile(String path) throws IOException {
// TODO Auto-generated method stub
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
}
You need to wait for the file to finish saving before you add it to the user.
Try adding a completion block to your file.saveInBackground() call, and moving all the currentUser manipulation into that completion block.