Can't send JSON data to other activity Android - java

I am quite new to Android.
What I am trying to do:
I downloaded data in JSON format through API. I am trying to Bundle it with some other data and send it over to my second activity.
My logic behind it is that I created a global variable "JSONData" and assigned the data I downloaded to it in "onPostExecute".
However when I try to send it through Intent (in a bundle) to the second activity only the first piece of data shows up.
My guess is that the bundle is sent before the JSON data is downloaded.
The data is definitely downloaded through API as I displayed it using TextView.
Anyone could give me some tips please on how to solve that??
I would be very grateful :)
public class MainActivity extends AppCompatActivity {
private String JSONData;
private TextView Data_Test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TestView = (TextView)findViewById(R.id.TestView);
}
public class JSONTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
JSONData = result;
/*Data_Test.setText(JSONData);*/
}
}
public void btnType0(View view) {
new JSONTask().execute("URL_with_API");
String activity_title = getResources().getString(R.string.housing_button);
Intent intent = new Intent(this, DisplayDataActivity.class);
Bundle extras = new Bundle();
extras.putString("title", activity_title);
extras.putString("JSON_Object", JSONData);
intent.putExtras(extras);
startActivity(intent);
}
In my second activity I receive the bundle as such:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_data);
Bundle bundle = getIntent().getExtras();
String activity_title = bundle.getString("title");
TextView txtView = (TextView) findViewById(R.id.txtTitle);
txtView.setText(activity_title);
String JSONData = bundle.getString("JSON_Object");
TextView txtView1 = (TextView) findViewById(R.id.data_test);
txtView1.setText(JSONData);
}

Man you are doing wrong!!
new JSONTask().execute("URL_with_API"); you can not get value in JSONData variable because you have declared it global were your assigning value in AsyncTask
which is background process, so this line will be went in background and next line will be executed immediately. below
String activity_title = getResources().getString(R.string.housing_button);
Intent intent = new Intent(this, DisplayDataActivity.class);
Bundle extras = new Bundle();
extras.putString("title", activity_title);
extras.putString("JSON_Object", JSONData);// so here JSONData always being null
intent.putExtras(extras);
startActivity(intent);
You have to start activity in onPostExecute like this
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String activity_title = getResources().getString(R.string.housing_button);
Intent intent = new Intent(this, DisplayDataActivity.class);
Bundle extras = new Bundle();
extras.putString("title", activity_title);
extras.putString("JSON_Object", result);
intent.putExtras(extras);
startActivity(intent);
}
public void btnType0(View view) {
new JSONTask().execute("URL_with_API");
}
Or just pass Url in required activity and fetch data in that activity using url in onCreate

You have to use like this.
Intent intent = new Intent(this,DisplayDataActivity.class);
//Bundle extras = new Bundle();
intent.putString("title", activity_title); intent.putString("JSON_Object", JSONData);
// intent.putExtras(extras);
startActivity(intent);

For send data
Intent intent = new Intent(this, DisplayDataActivity.class);
intent.putString("title", activity_title);
intent.putString("JSON_Object", JSONData);
startActivity(intent);
For Recieve data
String activity_title = getIntent().getExtras().getString("title");
String JSONData = getIntent().getExtras().getString("JSON_Object");

Related

Stored image URI for later use, but it throws SecurityException

In the SecondActivity, it has an ImageViewand a Button
public class SecondActivity extends AppCompatActivity
{
private ImageView galleryImage;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
galleryImage = findViewById(R.id.galleryImage);
Button openGalleryButton = findViewById(R.id.openGalleryButton);
openGalleryButton.setOnClickListener(view ->
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
activityResultLauncher.launch(intent);
});
/*...*/
}
}
for the activityResultLauncher, it is an ActivityResultLauncher that I used to open gallery and pick an Image.
ActivityResultLauncher<Intent> activityResultLauncher =
registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result ->
{
if (result.getResultCode() == Activity.RESULT_OK)
{
Intent data = result.getData();
if (data != null)
{
galleryImage.setImageURI(data.getData());
try
{
openFileOutput("uri", MODE_PRIVATE).write((data.getData() + "\n").getBytes());
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
});
As you can see, this not only shows the image that users pick, but also stores the uri string into a file for later use. But when I change to ThirdActivity, there is always a SecurityException stop me.
/*SecondActivity.java*/
Button showPickedButton = findViewById(R.id.showPickedButton);
showPickedButton.setOnClickListener(view ->
{
Intent thirdActivity = new Intent(SecondActivity.this, ThirdActivity.class);
thirdActivity.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(thirdActivity);
});
/*ThirdActivity.java*/
public class ThirdActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
LinkedList<String> uriStrings = new LinkedList<>();
String readImageURI;
try
{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(openFileInput("uri"), StandardCharsets.UTF_8));
while (true)
{
readImageURI = bufferedReader.readLine();
if (readImageURI != null)
uriStrings.add(readImageURI);
else
break;
}
}
catch (IOException e)
{
e.printStackTrace();
}
LinearLayout imagesList = findViewById(R.id.imagesList);
uriStrings.forEach(imageURIString ->
{
ImageView imageView = new ImageView(this);
imageView.setImageURI(Uri.parse(imageURIString));
imageView.setAdjustViewBounds(true);
imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
imagesList.addView(imageView);
});
}
}
The exception message:
As you can see, this not only shows the image that users pick, but also stores the uri string into a file for later use
That will not work with ACTION_PICK.
But when I change to ThirdActivity, there is always a SecurityException stop me.
For the purposes of using the Uri in the same process invocation as when you got it, you can pass the Uri along in the Intent:
Intent thirdActivity = new Intent(SecondActivity.this, ThirdActivity.class);
thirdActivity.setData(theImageUriThatWeAreTalkingAbout);
thirdActivity.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(thirdActivity);
However, that will not help for durable access via your persisted Uri value. Either get rid of that, or:
Switch to ACTION_OPEN_DOCUMENT instead of ACTION_PICK, and
Call takePersistableUriPermission() on a ContentResolver when you get the image Uri value
See this blog post for more.

Send the values of recycleview settext as intent

I have a recycleview in a card layout, the cards have 3 values set with a company array, I'm trying to send those values as an intent. But for some reason everything I try the intent ends up sending null
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
//companyList= new ArrayList<Company>();
//heres where the textviews get there values set
final Company company = companies.get(i);
viewHolder.textViewHead.setText(company.getCompanyTitle());
viewHolder.textviewDesc.setText(company.getCompanyType());
viewHolder.textViewNumber.setText(company.getCompanyNumber());
viewHolder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
///send these to nodes them attach the officers, get both in nodes and send to myview
companylist = new ArrayList<Company>();
//here are my ateempts try and send the values as intents
Company company1 = companies.get(i);
// view.getContext().startActivity(new Intent(view.getContext(), Nodes.class));
Intent skipintent = new Intent(view.getContext(), Nodes.class);
skipintent.putExtra(KEY_NAME, company.getCompanyTitle());
skipintent.putExtra(KEY_NAME,viewHolder.textViewHead.getText().toString());
skipintent.putExtra(KEY_TYPE, company1.getCompanyType());
skipintent.putExtra(KEY_NUMBER, company1.getCompanyNumber());
// view.getContext().startActivity(skipintent);
Bundle bundle = new Bundle();
bundle.putString("Companyname", company.getCompanyTitle());
bundle.putString(KEY_TYPE, company1.getCompanyType());
bundle.putString(KEY_NUMBER, company1.getCompanyNumber());
// bundle.putParcelableArrayList("Companyselected", companylist);
skipintent.putExtras(bundle);
new RetrieveFeedTask().execute(company1.getCompanyNumber());
}
});
}
And here is my activity where I am trying to receive it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_nodes);
//Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
//textViewNodes = (TextView) findViewById(R.id.textViewNodes);
// ArrayList<Company> recList = this.getIntent().getParcelableArrayListExtra("Company");
// companyList= new ArrayList <>();
ArrayList<Officer> officerArrayList = this.getIntent().getParcelableArrayListExtra("Officer");
// ArrayList<Company> companyArrayList = this.getIntent().getParcelableArrayListExtra("Companyselected");
Intent skipintent = getIntent();
Bundle bundle = getIntent().getExtras();
if (null != skipintent) { //Null Checking
Company company = new Company();
String companyTITLE = bundle.getString("Companyname");
String companyNUMBER = skipintent.getStringExtra(company.getCompanyNumber());
String companyTYPE = skipintent.getStringExtra(company.getCompanyType());
company.setCompanyNumber(companyNUMBER);
company.setCompanyTitle(companyTITLE);
company.setCompanyType(companyTYPE);
companyList.add(company);
Log.d("help", "onPostExecute: " + company.getCompanyTitle());
}
Log.d("meme", Arrays.toString(new ArrayList[]{companyList}));
here is the end of retrivefeed, I think I should send the values of the textviews here im not sure how
try {
JSONObject object = new JSONObject(response);
JSONArray itemsAraay = object.getJSONArray("items");
officerList = new ArrayList<Officer>();
Log.d("borkofficer", "onPostExecute: " + itemsAraay.length());
for (int i = 0; i < itemsAraay.length(); i++) {
Officer officer = new Officer();
JSONObject jsonObjectNew = itemsAraay.getJSONObject(i);
String name = jsonObjectNew.optString("name");
String role = jsonObjectNew.optString("officer_role");
String appointed_on = jsonObjectNew.optString("appointed_on");
//JSONArray.put(jsonObjectNew);
officer.setOfficerName(name);
officer.setOfficerRole(role);
officer.setOfficerAppointed(appointed_on);
officerList.add(officer);
Log.d("borkofficer", "onPostExecute: " + officer.getOfficerName());
Log.d("borkofficertitle", "onPostExecute: " + officer.getOfficerRole());
}
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("Officer", officerList);
//Intent skipintent = new Intent(view.getContext(), Nodes.class);
Intent intentofficer = new Intent(context.getApplicationContext(), Nodes.class);
intentofficer.putParcelableArrayListExtra("Officer", officerList);
Intent intentofficer1 = new Intent(context.getApplicationContext(), Nodes.class);
intentofficer1.putExtras(bundle);
// context.startActivity(intentofficer1);
intentofficer.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intentofficer1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.getApplicationContext().startActivity(intentofficer);
} catch (JSONException e) {
e.printStackTrace();
}
update im trying to bundle up the value and send in a intent but its still coming up null in the other activity is it because of the other intent im trying to send?
class RetrieveFeedTask extends AsyncTask {
private Exception exception;
protected String doInBackground(String... numbers) {
companylist = new ArrayList<Company>();
Company company = new Company();
String companynumber = numbers[0];
String companytitle = numbers[1];
String companytype = numbers[2];
company.setCompanyTitle(companytitle);
company.setCompanyType(companytype);
company.setCompanyNumber(companynumber);
companylist.add(company);
Bundle bundle1 = new Bundle();
Intent skipintent = new Intent(context.getApplicationContext(), Nodes.class);
skipintent.putExtra(KEY_NAME, companytitle);
skipintent.putExtra(KEY_NUMBER, companynumber);
skipintent.putExtra(KEY_TYPE, companytype);
skipintent.putParcelableArrayListExtra("Companylist", companylist);
skipintent.putExtras(bundle1);
Log.d("connect", "onPostExecute: " + companytitle.toString());
Log.d("connect", "onPostExecute: " + companytype.toString());
try {
URL url = new URL(API_URL + companynumber +"/officers");
Log.d("connect", "onPostExecute: " + companynumber.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Authorization", "uG5RCz7yWRZNKaMlkQRzUPXY1NpN0SRrb8mKSZ-0");
urlConnection.setReadTimeout(15000);
urlConnection.setConnectTimeout(15000);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if (response == null) {
response = "THERE WAS AN ERROR";
}
Log.i("INFO", response);
//does this store?
try {
JSONObject object = new JSONObject(response);
JSONArray itemsAraay = object.getJSONArray("items");
officerList = new ArrayList<Officer>();
Log.d("borkofficer", "onPostExecute: " + itemsAraay.length());
for (int i = 0; i < itemsAraay.length(); i++) {
Officer officer = new Officer();
JSONObject jsonObjectNew = itemsAraay.getJSONObject(i);
String name = jsonObjectNew.optString("name");
String role = jsonObjectNew.optString("officer_role");
String appointed_on = jsonObjectNew.optString("appointed_on");
//JSONArray.put(jsonObjectNew);
officer.setOfficerName(name);
officer.setOfficerRole(role);
officer.setOfficerAppointed(appointed_on);
officerList.add(officer);
Log.d("borkofficer", "onPostExecute: " + officer.getOfficerName());
Log.d("borkofficertitle", "onPostExecute: " + officer.getOfficerRole());
}
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("Officer", officerList);
//skipintent.putExtra(KEY_NUMBER, company1.getCompanyNumber());
// view.getContext().startActivity(skipintent);
//Bundle bundle = new Bundle();
// bundle.putString(KEY_NAME,);
//bundle.putString(KEY_TYPE, companylist.get(1).getCompanyType());
//bundle.putString(KEY_NUMBER, companylist.get(1).getCompanyNumber());
//company1.setCompanyTitle(;
//company1.setCompanyNumber(KEY_NUMBER);
// company1.setCompanyType(KEY_TYPE);
// companylist.add(company1);
// bundle.putParcelableArrayList("Companyselected", companylist);
//skipintent.putExtras(bundle);
Intent intentofficer = new Intent(context.getApplicationContext(), Nodes.class);
intentofficer.putParcelableArrayListExtra("Officer", officerList);
Intent intentofficer1 = new Intent(context.getApplicationContext(), Nodes.class);
intentofficer1.putExtras(bundle);
// context.startActivity(intentofficer1);
intentofficer.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intentofficer1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.getApplicationContext().startActivity(intentofficer);
Inside the activity, try to extract values with same keys as were used in adapter. Use
String companyNUMBER = skipintent.getStringExtra(KEY_NUMBER);
String companyTYPE = skipintent.getStringExtra(KEY_TYPE);
instead of
String companyNUMBER = skipintent.getStringExtra(company.getCompanyNumber());
String companyTYPE = skipintent.getStringExtra(company.getCompanyType());
UPDATE
To start activity inside the AsyncTask, pass data as a constructor parameter: new RetrieveFeedTask(company.getCompanyName()).
private String mCompanyName;
RetrieveFeedTask(String companyName) {
this.mCompanyName = companyName;
}
and then use it as usually to put in the intent:
intent.putExtra(KEY_NAME, mCompanyName);
UPDATE 2
As an alternative, you can pass data in the new RetrieveFeedTask().execute(company1.getCompanyNumber(), company1.getCompanyTitle(), company1.getCompanyType()) method and use them in doInBackground:
String doInBackground(String... data) {
String companyNumber = data[0];
String companyTitle = data[1];
String companyType = data[2];
// ...
}

Failed to send image from one activity to another. Please see details

I'm fetching user's profile picture from facebook and I want to send it to ProfileActivity.java so that it can be displayed on user profile.
The problem is that the image is not getting sent from SignUpScreen.java to ProfileActivity.java. Though I am able to send name & email from one to another.
Here's SignUpScreen.java file's code:
public class SignUpScreen extends AppCompatActivity {
Button facebookLoginButton;
CircleImageView mProfileImage;
TextView mUsername, mEmailID;
Profile mFbProfile;
ParseUser user;
Bitmap bmp = null;
public String name, email, userID;
public static final List<String> mPermissions = new ArrayList<String>() {{
add("public_profile");
add("email");
}};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_sign_up_screen);
TextView textView = (TextView) findViewById(R.id.h);
Typeface typeface = Typeface.createFromAsset(getBaseContext().getAssets(), "fonts/Pac.ttf");
textView.setTypeface(typeface);
mProfileImage = (CircleImageView) findViewById(R.id.user_profile_image);
mUsername = (TextView) findViewById(R.id.userName);
mEmailID = (TextView) findViewById(R.id.aboutUser);
mFbProfile = Profile.getCurrentProfile();
//mUsername.setVisibility(View.INVISIBLE);
//mEmailID.setVisibility(View.INVISIBLE);
facebookLoginButton = (Button) findViewById(R.id.facebook_login_button);
facebookLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ParseFacebookUtils.logInWithReadPermissionsInBackground(SignUpScreen.this, mPermissions, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d("MyApp", "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d("MyApp", "User signed up and logged in through Facebook!");
getUserDetailsFromFacebook();
final Handler handler3 = new Handler();
handler3.postDelayed(new Runnable() {
#Override
public void run() {
saveNewUser();
}
}, 5000);
} else {
Log.d("MyApp", "User logged in through Facebook!");
}
}
});
}
});
}
public void saveNewUser() {
user = new ParseUser();
user.setUsername(name);
user.setEmail(email);
user.setPassword("hidden");
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(SignUpScreen.this, "SignUp Succesful", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(SignUpScreen.this, "SignUp Unsuccesful", Toast.LENGTH_LONG).show();
Log.d("error when signingup", e.toString());
}
}
});
}
private void getUserDetailsFromFacebook() {
final GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
//Log.d("response", "response" + object.toString());
Intent profileIntent = new Intent(SignUpScreen.this, ProfileActivity.class);
Bundle b = new Bundle();
try {
name = response.getJSONObject().getString("name");
mUsername.setText(name);
email = response.getJSONObject().getString("email");
mEmailID.setText(email);
userID = response.getJSONObject().getString("id");
new ProfilePicAsync().execute(userID);
b.putString("userName", name);
b.putString("userEmail", email);
profileIntent.putExtras(b);
profileIntent.putExtra("user_pic", bmp);
startActivity(profileIntent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name, email, id");
request.setParameters(parameters);
request.executeAsync();
}
class ProfilePicAsync extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String imageURL;
String id = userID;
imageURL = "https://graph.facebook.com/"+ id +"/picture?type=large";
try {
bmp = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
} catch (Exception e) {
e.printStackTrace();
Log.d("Loading picture failed", e.toString());
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mProfileImage.setImageBitmap(bmp);
}
}
}
Here's ProfileActivity.java file's code:
public class ProfileActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Bundle bundle = getIntent().getExtras();
CircleImageView mProfileImage = (CircleImageView) findViewById(R.id.user_profile_image);
TextView mUsername = (TextView) findViewById(R.id.userName);
TextView mEmailID = (TextView) findViewById(R.id.aboutUser);
Bitmap bitmap = (Bitmap) getIntent().getParcelableExtra("user_pic");
mProfileImage.setImageBitmap(bitmap);
mUsername.setText(bundle.getString("userName"));
mEmailID.setText(bundle.getString("userEmail"));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
Please let me know what is going wrong here.
In your getUserDetailsFromFacebook() method you have called new ProfilePicAsync().execute(userID) to get the image. But it seems that before you could fetch the image ,startActivity(profileIntent) probably gets called.
First be sure that you have fetched the image from facebook before you call startActivity(profileIntent).
EDIT
Add this to your getUserDetailsFromFacebook() ,
b.putString("userName", name);
b.putString("userEmail", email);
profileIntent.putExtras(b);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
profileIntent.putExtra("user_pic", byteArray);
startActivity(profileIntent);
Add this to your ProfileActivity.java ,
byte[] byteArray = getIntent().getByteArrayExtra("user_pic");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
mProfileImage.setImageBitmap(bmp);
This is not a right way to pass image from Activity to Activity within same application. You can easily send the path by intent and load it into other Activity.
To save a bitmap in Activity A, use
FileOutputStream out = null;
try {
out = new FileOutputStream(FILENAME); //FILENAME is your defined place to store image
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Now you have FILENAME global string which is accessible from Activity B.
Just load it where its needed.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(FILENAME, options);
mProfileImage.setImageBitmap(bitmap);
it works for me.
OneActivity.java
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Intent intent = new Intent(StartPage.this, SecondActivity.class);
Toast.makeText(StartPage.this, "You have setted this wallpaper for Monday", Toast.LENGTH_LONG).show();
intent.putExtra("pic", byteArray);
//intent.putExtra("resourseInt", bm);
startActivity(intent);
SecondActivity.Java
byte[] byteArray;
Bitmap bmp,
byteArray = getIntent().getByteArrayExtra("pic");
bmp1 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
myWallpaperManager.setBitmap(bmp);

directing to Activity from Asynctask

this is the LoginActivty
public class MainActivity extends Activity {
ProgressDialog prgDialog;
TextView errorMsg;
EditText emailET;
EditText pwdET;
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
errorMsg = (TextView) findViewById(R.id.login_error);
emailET = (EditText) findViewById(R.id.loginEmail);
pwdET = (EditText) findViewById(R.id.loginPassword);
prgDialog = new ProgressDialog(this);
prgDialog.setMessage("Please wait...");
prgDialog.setCancelable(false);
button = (Button) findViewById(R.id.btnLogin);
final Button button = (Button) findViewById(R.id.btnLogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Get Email Edit View Value
String email = emailET.getText().toString();
// Get Password Edit View Value
String password = pwdET.getText().toString();
// When Email Edit View and Password Edit View have values
// other than Null
if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
// When Email entered is Valid
if (Utility.validate(email)) {
// call the async task
JSONObject js = new HttpAsyncTask(
getApplicationContext()).execute(email,
password).get();
Toast.makeText(getApplicationContext(),
"Asynctask started", Toast.LENGTH_SHORT)
.show();
}
// When Email is invalid
else {
Toast.makeText(getApplicationContext(),
"Please enter valid email",
Toast.LENGTH_LONG).show();
}
}
// When any of the Edit View control left blank
else {
Toast.makeText(
getApplicationContext(),
"Please fill the form, don't leave any field blank",
Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
}
}
});
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
}
});
}
}
then I am using a AsyncTask, this the code
public class HttpAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private static InputStream stream = null;
private static String API;
private JSONObject responseJson = null;
private Context contxt;
private Activity activity;
public HttpAsyncTask(Context context) {
// API = apiURL;
this.contxt = context;
}
// async task to accept string array from context array
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the username and password
Log.i("Email", params[0]);
Log.i("Password", params[1]);
try {
path = "http://192.168.x.xxx/xxxxService/UserAuthentication";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("Email"), params[0]);
request.put(new String("Password"), params[1]);
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String myResJson;
try {
myResJson = responseJson.getString("status");
String test = myResJson;
if (test.equals("200")) {
Log.i("Login Success", "Success message");
} else {
Log.e("Login Error", "Error converting result ");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
when I enter correct email and password, it comes to this line
Log.i("Login Success", "Success message");
from there I want to open the HomeActivty but it doesn't allow me to use intent, or even to toast
I need help to implement directing to Home Activity once the logging is success.
Here:
JSONObject js = new HttpAsyncTask(
getApplicationContext()).execute(email,
password).get();
Because you are getting result on Main Thread by calling AsyncTask.get() method AsyncTask.
First just call AsyncTask.execute method to start AsyncTask task :
new HttpAsyncTask(MainActivity.this).execute(email,password);
then use onPreExecute() to show progessbar and onPostExecute for starting next Activity :
#Override
protected void onPreExecute() {
// show ProgressDialog here
}
#Override
protected void onPostExecute(Void result) {
// parse json here and start Home Activity
//.........your code here
if (test.equals("200")) {
Log.i("Login Success", "Success message");
Intent intent = new Intent(contxt,HomeActivity.class);
contxt.startActivity(intent);
} else {
Log.e("Login Error", "Error converting result ");
}
}
You can start activity like this from AsyncTask, You should use the context.
mContext.startActivity(new Intent(CurrentActivity.this, Home.class));
Or try like this also
Intent intent = new Intent();
intent.setClass(getApplicationContext(),Home.class);
startActivity(intent);
I know there is another valid answer to fix your problem. But to precisely explain why your error exists, I give my answer below.
To create an Intent for startActivity(), this can be done by:
Intent i = new Intent(currentActivity, NextActivity.class);
startActivity(i);
Notice that the first parameter of constructor of Intent is android.content.Context, in which Activity is a subclass of it. So in any situation, you can always pass the Context to your custom class and start a new Activity or create a Toast with this Context.
In your question, private Context contxt; in HttpAsyncTask is the context your need to do everything.
Reference: http://developer.android.com/reference/android/content/Intent.html#Intent%28android.content.Context,%20java.lang.Class%3C?%3E%29

In Android: How can i send the result of from OnPostExecute() to other activity?

I got the result of OnPostExecute() to main activity but I want to use this result in second activity. I read and applied something with using Bundle but it doesn't run. I got error NullPointerException cause of not receiving the value in the second activity. Here is my MainActivity (It has an interface AsyncResponse ):
public class MainActivity extends Activity implements AsyncResponse
{
public String t;
public Bundle bnd;
public Intent intent;
public String sending;
private static final String TAG = "MyActivity";
ProductConnect asyncTask =new ProductConnect();
public void processFinish(String output){
sending=output;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
asyncTask.delegate = this;
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
bnd=new Bundle();
intent=new Intent(MainActivity.this, second.class);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
asyncTask.execute(true);
bnd.putString("veri", sending);
intent.putExtras(bnd);
startActivity(intent);
}
});
}
// START DATABASE CONNECTION
class ProductConnect extends AsyncTask<Boolean, String, String> {
public AsyncResponse delegate=null;
private Activity activity;
public void MyAsyncTask(Activity activity) {
this.activity = activity;
}
#Override
protected String doInBackground(Boolean... params) {
String result = null;
StringBuilder sb = new StringBuilder();
try {
// http post
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(
"http://192.168.2.245/getProducts.php");
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error");
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF8"));
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
Log.d("test", result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
t = json_data.getString("name");
delegate.processFinish(t);
}
} catch (JSONException e1) {
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
super.onPostExecute(result);
}
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Please wait");
pd.setMessage("Authenticating..");
pd.show();
}
}
Here is My Second Activity:
public class second extends ActionBarActivity {
public CharSequence mTitle;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Bundle receive=getIntent().getExtras();
String get=receive.getString("veri");
Log.v(TAG, get);
}
What should i do?
AsyncTask.execute() is a non-blocking call. You can't set the result to the Bundle and start an Intent immediatly after execute(). That's why you are getting a NPE in your second Activity because sending isn't initialized, so it's null.
Move the code to start a new Activity with the desired data in your callback:
public void processFinish(String output){
bnd.putString("veri", output);
intent.putExtras(bnd);
startActivity(intent);
}
And make sure you call delegate.processFinished(String) if your data processing is finished. So move it out of the for loop. BTW t will only get the last "name"-String in the JSONArray. If you wanna get them all make t a String array and fill it.
As your variable t is globally declared in your activity so can directly use the value of t which you are assigning in your onPostExecute() method. Just you need to check for its null value only in your button click event as below :
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
asyncTask.execute(true);
if(t != null || t != "")
{
bnd.putString("veri", t);
intent.putExtras(bnd);
startActivity(intent);
}
}
});
// try this
public class MainActivity extends Activity
{
public String t;
public Bundle bnd;
public Intent intent;
private static final String TAG = "MyActivity";
ProductConnect asyncTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
bnd=new Bundle();
intent=new Intent(MainActivity.this, second.class);
asyncTask = new ProductConnect(new ResultListener() {
#Override
public void onResultGet(String value) {
bnd.putString("veri", value);
intent.putExtras(bnd);
startActivity(intent);
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
asyncTask.execute(true);
}
});
}
class ProductConnect extends AsyncTask<Boolean, String, String> {
private ResultListener target;
public ProductConnect(ResultListener target) {
this.target = target;
}
#Override
protected String doInBackground(Boolean... params) {
String result = null;
StringBuilder sb = new StringBuilder();
try {
// http post
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(
"http://192.168.2.245/getProducts.php");
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error");
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF8"));
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
Log.d("test", result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
t = json_data.getString("name");
target.onResultGet(t);
}
} catch (JSONException e1) {
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
super.onPostExecute(result);
}
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Please wait");
pd.setMessage("Authenticating..");
pd.show();
}
}
interface ResultListener {
public void onResultGet(String value);
}
}
Shortly before someone posted a solution and it works without any errors but it was deleted. This solution is by this way:
public void onClick(View arg0) {
asyncTask.execute(true);
}
});
}
Then OnPostExecute changed like this:
protected void onPostExecute(String result) {
Intent passValue=new Intent(MainActivity.this, second.class);
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
t = json_data.getString("name");
delegate.processFinish(t);
}
passValue.putExtra("veri", t);
startActivity(passValue);
} catch (JSONException e1) {
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
super.onPostExecute(result);
}
Lastly in my second activity receive the string by this way:
String receivedVal= getIntent().getExtras().getString("veri");
Log.v(TAG, receivedVal);
Thank you someone who posted this solution shortly before :)

Categories