I'm using android studio to get information from user and insert it into external DB, and i saw a lot of videos in youtube but still there is a problem when run it says: "registration success" but doesn't insert into DB
This is my code in android studio
public class signup extends AppCompatActivity {
EditText email,password,name;
Switch visually_impaired;
String Email,Password,Name,Visually_impaired,Beacon_alert,Buildings_alert;;
Context ctx = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
name = (EditText) findViewById(R.id.name_editText);
password = (EditText) findViewById(R.id.password_editText);
email = (EditText) findViewById(R.id.email_editText);
visually_impaired = (Switch) findViewById(R.id.blindOpt);
}
public void register(View v){
Email = email.getText().toString();
Name = name.getText().toString();
Password = password.getText().toString();
Visually_impaired = visually_impaired.getText().toString();
BackGround b = new BackGround(this);
b.execute(Email,Password,Name,Visually_impaired);
}
class BackGround extends AsyncTask<String,String,String> {
Context ctx;
public BackGround(Context ctx){
this.ctx = ctx;
}
#Override
protected String doInBackground(String... strings) {
String email = strings[0];
String password = strings[1];
String name = strings[2];
String visually_impaired = strings[3];
try {
URL url = new URL("http://ksuexpress.com/register.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter bufferWriter = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
String data = URLEncoder.encode("email","UTF-8")+ " = "+URLEncoder.encode(email,"UTF-8") +"&"+
URLEncoder.encode("password","UTF-8")+ " = "+URLEncoder.encode(password,"UTF-8") +"&"+
URLEncoder.encode("name","UTF-8")+ " = "+URLEncoder.encode(name,"UTF-8") +"&"+
URLEncoder.encode("visually_impaired","UTF-8")+ " = "+URLEncoder.encode(visually_impaired,"UTF-8");
bufferWriter.write(data);
bufferWriter.flush();
bufferWriter.close();
os.close();
InputStream is = httpURLConnection.getInputStream();
is.close();
return "Registration success....";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();
}
}
}
and also i have a php code in server that uses POST and insert it to the DB
can anyone help me please ...
Some possible fixes:
change " = " to "=" without spaces
add some logs in doInBackground and make sure you're getting the correct parameters into email,password,etc.
change InputStream is = httpURLConnection.getInputStream(); is.close(); to httpURLConnection.connect();
Related
I am back from taking a few years break in programming. Today I am trying to access my webserver from android and I have some code I recycled from back in the day. The code used to work, but, lo and behold, today it has an error. Can someone help me figure this out?
Here is my main class:
public class login extends AppCompatActivity {
Button join;
TextView clientid;
EditText username, password;
_upload upload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
upload = new _upload();
String android_id = Secure.getString(login.this.getContentResolver(),
Secure.ANDROID_ID);
join = findViewById(R.id.join);
clientid = findViewById(R.id.clientid);
clientid.setText(android_id);
username = findViewById(R.id.username);
password = findViewById(R.id.password);
join.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login();
}});
}
public void login(){
String id = username.getText().toString();
if (id.isEmpty()) { username.setError("required");username.requestFocus();return; }
String pw = password.getText().toString();
String cid = clientid.getText().toString();
String[] params = new String[3];
params[1]="username::" + id;
params[2]="password::" + pw;
params[3]="cid::" + cid;
new upload.send(login.this, "dump.php", params);
Toast.makeText(this, id + " " +pw+ " "+cid, Toast.LENGTH_LONG).show();
}
}
my error is in the line new upload.send(login.this, "dump.php", params);
error: cannot find symbol
new _upload.send(login.this, "dump.php", params);
^
symbol: class send
location: class _upload
this is my second class, the one that used to work:
public class _upload extends AppCompatActivity {
HttpURLConnection conn = null;
String Return;
String homeurl = "removed";
String roomurl = "";
String param;
Context ctx;
String er;
public void location(Context context, String url, String params){
ctx = context;
roomurl = url;
try {
param = "lola=" + URLEncoder.encode(params, "UTF-8");
new sendStatusChange_Server().execute("");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public void send(Context context, String url, String params[]){
ctx = context;
roomurl = url;
int total = params.length;
int i = 0;
while(i<=total-1) {
if (i==0) {
try {
String[] keyval = params[0].split("::");
param = keyval[0] + "=" + URLEncoder.encode(keyval[1], "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
else{
try {
String[] keyval = params[i].split("::");
param = param + "&" + keyval[0] + "=" + URLEncoder.encode(keyval[1], "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
}
new sendStatusChange_Server().execute("");
}
public class sendStatusChange_Server extends AsyncTask<String, String, Void> {
protected Void doInBackground(String... params) {
try {
updateserver();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(er!=null){Toast.makeText(ctx, er, Toast.LENGTH_LONG).show();}
else{Toast.makeText(ctx, Return, Toast.LENGTH_LONG).show();}
}
}
private void updateserver() throws IOException {
URL url = new URL(homeurl + roomurl);
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(param.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(param);
Log.d("SENT:", param + " to " + url.toString());
out.close();
String response = "";
Scanner inStream = new Scanner(conn.getInputStream());
while (inStream.hasNextLine())
response += (inStream.nextLine());
inStream.close();
Return = response;
} catch (MalformedURLException ex) {
} catch (IOException ex) {
er = ex.toString();
}
return;
}
}
the code still runs fine on the old program but I made a new package and want to get that rolling... why would this happen? Thank you for taking the time!
You have a syntax error. Use
upload.send(...)
instead of
new upload.send(...)
since upload is already an instance of your class.
You should probably also make it so _upload doesn't extend AppCompatActivity (just remove the extends AppCompatActivity from public class _upload extends AppCompatActivity).
Basically, I want to start a new activity after login using the database. How can I do that?
This is my login class
public class login extends AppCompatActivity {
EditText username;
EditText password;
Button btn_login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
btn_login = (Button) findViewById(R.id.btn_login);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String user = username.getText().toString();
String pass = password.getText().toString();
String type = "login";
System.out.println("IN Onclick login");
BackgroundTask backgroundTask = new BackgroundTask(getApplicationContext());
backgroundTask.execute(type,user,pass);
if(backgroundTask.statusOK.equals("true")) {
Intent loginIntent = new Intent(login.this,loggedIn.class);
startActivity(loginIntent);
}
}
});
}
}
You can see in the code above that I am using this code to start my new activity after successful login, but this is not starting a new activity. I don't know why?
if(backgroundTask.statusOK.equals("true")) {
Intent loginIntent = new Intent(login.this,loggedIn.class);
startActivity(loginIntent);
}
This is BackgroundTask class
public class BackgroundTask extends AsyncTask<String, String, String> {
Context context;
public String statusOK="false";
BackgroundTask(Context ctx){
this.context = ctx;
}
#Override
protected String doInBackground(String... strings) {
System.out.println("In doin");
String type = strings[0];
String loginURL = "http://192.168.10.119/log/login.php";
String regURL = "http://192.168.10.119/log/log.php";
if(type.equals("reg")){
String name = strings[1];
String pass = strings[2];
try{
URL url = new URL(regURL);
try {
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String insert_data = URLEncoder.encode("Username","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+
"&"+URLEncoder.encode("Password","UTF-8")+ "=" +URLEncoder.encode(pass,"UTF-8");
bufferedWriter.write(insert_data);
bufferedWriter.flush();
bufferedWriter.close();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"ISO-8859-1");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String result="";
String line="";
StringBuilder stringBuilder = new StringBuilder();
while((bufferedReader.readLine())!= null){
stringBuilder.append(line).append("\n");
}
result = stringBuilder.toString();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
else if(type.equals("login")){
System.out.println("In type = login");
String name1 = strings[1];
String pass1 = strings[2];
try{
URL url = new URL(loginURL);
try {
System.out.println("In type = login try");
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String login_data = URLEncoder.encode("Username","UTF-8")+"="+URLEncoder.encode(name1,"UTF-8")+
"&"+URLEncoder.encode("Password","UTF-8")+ "=" +URLEncoder.encode(pass1,"UTF-8");
bufferedWriter.write(login_data);
bufferedWriter.flush();
bufferedWriter.close();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"ISO-8859-1");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String result="";
String line="";
StringBuilder stringBuilder = new StringBuilder();
while((bufferedReader.readLine())!= null){
stringBuilder.append(line).append("\n");
}
result = stringBuilder.toString();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
statusOk="true";
Toast.makeText(context, "Successful", Toast.LENGTH_LONG).show();
//super.onPostExecute(s);
}
}
I have checked the connection between the database and my app is established and the app is running without any error.
You can see in the code above that I have created a public variable statusOk and initialize it with "false". This variable is telling the login class that the user have entered his correct login credentials.
You can see that I have changed the value of statusOk to "true" onPostExexute method.
Now the problem is my new activity is not opening from the login class after successful login. Please give me a solution how can I open a new activity after Login with correct login credentials.
Asynctask is used to execute task in the background thread, (not the main thread from where you have called the execute() ).
Therefore in your code, if statement is executed just after you called the execute(), which still store the variable statusOK as false. Hence the condition is false.
The postExecute() method of asynctask is used to execute code in the main thread,
My suggestion: remove the if condition from the Login class, and check for the if condition in the postExecute(),
Here is my Register.php
<?php
require "init.php";
$name=$_POST["user"];
$user_name = $_POST["user_name"];
$user_pass = $_POST["user_pass"];
$sql_query = "insert into user_info values('$user','$user_name','$user_pass');";
if(mysqli_query($con,$sql_query)) {
//echo "Data Insertion Success...";
} else {
//echo "Data Insertion Error...".mysqli_error($con);
}
Here is the Register Activity.
public class Register extends Activity {
String naam,username,pass;
EditText new_user_pass;
EditText new_user_name;
EditText name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
new_user_name = (EditText) findViewById(R.id.new_user_name);
new_user_pass = (EditText) findViewById(R.id.new_user_pass);
name = (EditText) findViewById(R.id.name);
}
public void userReg(View view)
{
naam = name.getText().toString();
username = new_user_name.getText().toString();
pass = new_user_pass.getText().toString();
String method;
method="register";
Backend backEnd = new Backend(this);
backEnd.execute(method,naam,username,pass);
finish();
}
}
Here is the back end activity.
public class Backend extends AsyncTask<String,Void,String> {
Context ctx;
Backend(Context ctx)
{
this.ctx=ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String reg_url="http://192.168.0.7/app/register.php";
String login_url="http://192.168.0.7/app/register.php";
String method = params[0];
if(method.equals("register")){
String naam=params[1];
String username=params[2];
String pass=params[3];
try {
URL url = new URL (reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS,"UTF-8"));
String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(naam,"UTF-8") + "&"+
URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(username,"UTF-8") +"&"+
URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(pass,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Registration Success";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return reg_url;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate();
}
}
I am trying to insert inputs to database but whenever I try, it adds empty rows to it. I have created an html form that works perfectly. Here is my code I would appreciate any help.
MyFragment.java
public class MyFragment extends Fragment{
EditText senderEt, headerEt, textEt;
Button btn;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.my_fragment, container, false);
senderEt = (EditText)rootView.findViewById(R.id.sender);
headerEt = (EditText)rootView.findViewById(R.id.header);
textEt = (EditText)rootView.findViewById(R.id.text);
btn = (Button) rootView.findViewById(R.id.btnSend);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addToDB(getView());
}
});
return rootView;
}
public void addToDB(View view){
String sender= senderEt.getText().toString();
String header= headerEt.getText().toString();
String text= textEt.getText().toString();
BackgroundTask backgroundTask = new BackgroundTask(getActivity());
backgroundTask.execute(sender, header, text);
}
}
BackgroundTask.java
public class BackgroundTask extends AsyncTask<String, Void, String> {
Context context;
BackgroundTask(Context context){
this.context=context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String add_url= "http://139.179.196.153:8080/addDB.php";
String sender = params[0];
String header = params[1];
String text = params[2];
try {
URL url = new URL(add_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode("sender", "UTF-8") + " = "+URLEncoder.encode(sender, "UTF-8")+"&"+
URLEncoder.encode("header", "UTF-8") + " = "+URLEncoder.encode(header, "UTF-8")+"&"+
URLEncoder.encode("text", "UTF-8") + " = "+URLEncoder.encode(text, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inpInputStream = httpURLConnection.getInputStream();
inpInputStream.close();
return "Add to DB Success";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String res) {
Toast.makeText(context, res, Toast.LENGTH_SHORT).show();
}
}
After I debugged, I got "data" variable in "BackgroundTask" as
sender = fggff&header = kkkjjj&text = qwwqwq
do they have to be in quotes? or are the blanks problem?
php code
<?php
$db_name = "test";
$db_user = "root";
$db_password = "";
$db_server_name = "localhost";
$con = new mysqli($db_server_name, $db_user, $db_password, $db_name);
if($con->connect_error){
echo "Connection error".mysqli_connect_error();
}
else{
echo "<h3>Database connection success</h3>";
}
$sender = $_POST["sender"];
$header = $_POST["header"];
$text = $_POST["text"];
$sql_query = "insert into things values('$sender','$header','$text')";
if(mysqli_query($con, $sql_query)){
echo "<h3>Data insertion success</h3>";
}
else{
echo "<Data insertion error</h3>".mysqli_error($con);
}
Keep in mind that your background task will not do the inserts immediately when called. I think you are passing reference parameters (that is not scalars) and so the caller could be changing them before the background task has a chance to use them.
Two choices: don't do in background - for a local db, a single insert is really fast and can usually be done on the UI thread.
Or, make copies of the strings before you send them to the background task.
When i try to set the ImageView variable "profilePicture" to the bitmap from the image url, it doesn't show anything. Please help!! I am getting the image url link from my database. This is what that async task result is.
System.out: Resulted Value: {"image":"http://www.myegotest.com/PhotoUpload/uploads/5.png"}
Here is my Java code
public class HomeActivity extends AppCompatActivity {
//View item variables
private TextView loggedUsersName;
private TextView successMessage;
private Button logoutButton;
private ImageView profilePicture;
//Other variables
private String getProfileImageURL = "http://www.myegotest.com/PhotoUpload/getAllImages.php";
private String firstName;
private String lastName;
private String email;
private Bitmap profilePicBitmap;
LocalDataBase mLocalDataBase;
Boolean imageSet;
Drawable d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//Get logged in user from LocalDataBase and
//Destroy Activity if user is logged out
mLocalDataBase = new LocalDataBase(this);
User user = mLocalDataBase.getLoggedInUserInfo();
if(!mLocalDataBase.userIsLoggedIn()){
HomeActivity.this.finish();
}
//Initialize view item variables.
loggedUsersName = (TextView)findViewById(R.id.login_user);
successMessage = (TextView)findViewById(R.id.message);
logoutButton = (Button)findViewById(R.id.logoutButton);
profilePicture = (ImageView)findViewById(R.id.profile_Picture);
//Get intent and values from the intent started this activity and
//Get loggedIn user values from the LocalDataBase .
Intent intent = getIntent();
String message = intent.getStringExtra("MESSAGE");
firstName = user.mFirstName;
lastName = user.mLastName;
email = user.mEmail;
//Set view values to equal values sent from intent.
loggedUsersName.setText(firstName + " " + lastName);
successMessage.setText(message);
netAsync();
}
//Call this method to execute the Async Task
private void netAsync() {
new NetCheck().execute();
}
//Async Task to check whether internet connection is working.
private class NetCheck extends AsyncTask {
private ProgressDialog mDialog;
//Create and show progress dialog box so user knows the app is trying to login.
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog = new ProgressDialog(HomeActivity.this);
mDialog.setTitle("Logging In...");
mDialog.setMessage("connecting to server");
mDialog.setIndeterminate(false);
mDialog.setCancelable(true);
mDialog.show();
}
//Gets current device state and checks for working internet connection by trying Google.
#Override
protected Boolean doInBackground(Object[] objects) {
ConnectivityManager mCM = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetInfo = mCM.getActiveNetworkInfo();
if ( (myNetInfo != null) && (myNetInfo.isConnected())){
try {
URL url = new URL("http://google.com");
HttpURLConnection myConnection = (HttpURLConnection) url.openConnection();
myConnection.setConnectTimeout(3000);
myConnection.connect();
if (myConnection.getResponseCode() == 200){
return true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
//If successful internet connection start AsyncTask to register user info on server
if(o.equals(true)){
mDialog.dismiss();
new RegisterUser().execute(getProfileImageURL, email);
} else {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), "Error in Network Connection", Toast.LENGTH_SHORT).show();
}
}
}
//AsyncTask to get profile pic url string from server
private class RegisterUser extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection LucasHttpURLConnection = (HttpURLConnection)url.openConnection();
LucasHttpURLConnection.setRequestMethod("POST");
LucasHttpURLConnection.setDoOutput(true);
LucasHttpURLConnection.setDoInput(true);
LucasHttpURLConnection.setConnectTimeout(1000 * 6);
LucasHttpURLConnection.setReadTimeout(1000 * 6);
//OutputStream to get response
OutputStream outputStream = LucasHttpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data =
URLEncoder.encode("email", "UTF-8")+"="+URLEncoder.encode(params[1], "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//InputStream to get response
InputStream IS = LucasHttpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "iso-8859-1"));
StringBuilder response = new StringBuilder();
String json;
while( (json = bufferedReader.readLine()) != null){
response.append(json + "\n");
break;
}
bufferedReader.close();
IS.close();
LucasHttpURLConnection.disconnect();
return response.toString().trim();
} catch (MalformedInputException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Print server AsyncTask response
System.out.println("Resulted Value: " + result);
//If null Response
if (result != null && !result.equals("")) {
String profilepic = returnParsedJsonObject(result);
new GetBitmapImageFromUrl().execute(profilepic);
profilePicture = (ImageView)findViewById(R.id.profile_Picture);
profilePicture.setImageBitmap(profilePicBitmap);
} else {
Toast.makeText(HomeActivity.this, "Sorry, there was an error. Please try again", Toast.LENGTH_LONG).show();
}
}
//Method to parse json result and get the value of the key "image"
private String returnParsedJsonObject(String result){
JSONObject resultObject = null;
String returnedResult = "";
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getString("image");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
}
class GetBitmapImageFromUrl extends AsyncTask<String,Void,Bitmap>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... params) {
try {
profilePicBitmap = BitmapFactory.decodeStream((InputStream)new URL(params[0]).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
}
}
}
If you are seeing background white instead image. Out of memory exception by using bitmap.
You could use
Option 1
URL newurl = new URL(photo_url_str);
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
profile_photo.setImageBitmap(mIcon_val);
Picasso
Picasso.with(context).load("http://www.myegotest.com/PhotoUpload/uploads/5.png").into(profilePicture);
I would suggest to go with Piccasso. Since it will handle everything.