Android code to connect PHP response changed to null - java

I'm facing problem in getting a response back in android from PHP.
First, it gets the right response in try then I don't know what cause problem it goes to catch and change response to null. My PHP files are perfectly working I tested them by giving default values.
Below is the code:
This class is used to connect to server and send data to PHP:
public class DatabaseFunctionality extends AsyncTask <String, String, String>{
int flag;
Context context;
String username;
String password;
String rname;
String city;
int mnum;
String sname;
String area;
String sadd;
int snum1;
int snum2;
String cpic;
String ppic;
Bitmap coverpic, profpic;
public String resp;
//public String r;
StringBuilder sb;
public DatabaseFunctionality(Context context, int f){
this.context=context;
this.flag=f;
}
#Override
protected String doInBackground(String... params) {
if(this.flag==0){
username=params[0];
password=params[1];
resp = login();
}
else if(this.flag==1){
rname = params[0];
username = params[1];
password = params[2];
city = params[3];
mnum = Integer.parseInt(params[4]);
sname = params[5];
area = params[6];
sadd = params[7];
snum1 = Integer.parseInt(params[8]);
snum2 = Integer.parseInt(params[9]);
resp = signup();
}
return resp;
}
public String login() {
try {
String link = "http://192.168.0.105:80/directdukan/login.php";
String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
Log.e("string", sb.toString());
return sb.toString();
}
catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
public String signup(){
try{
String link = "http://192.168.0.105:80/directdukan/signup.php?rname="+rname+"&username="+username+"&password="+password+"&city="+city+"&mnum="+mnum+"&sname="+sname+"&area="+area+"&sadd="+sadd+"&sanum1="+snum1+"&snum2="+snum2;//+"& cpic="+coverpic+"& ppic="+profpic;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
Log.e("string", sb.toString());
return sb.toString();
} catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
public void addproduct(){
}
public void searchproduct(){
}
public void editproduct(){
}
public void deleteproduct(){
}
#Override
protected void onPostExecute(String result){
this.resp = result;
}
public Bitmap StringToBitMap(String encodedString){
try {
byte [] encodeByte=Base64.decode(encodedString, Base64.DEFAULT);
Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch(Exception e) {
e.getMessage();
return null;
}
}
}
// Below LoginActivity & SignupActivity is used to get data from activity and send it to DatabaseFunctionality class
public class LoginActivity extends AppCompatActivity {
EditText username, password;
Button login, signup;
#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);
login = (Button) findViewById(R.id.button_login);
signup = (Button) findViewById(R.id.button_signup);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String uname = username.getText().toString();
String pass = password.getText().toString();
if(!"".equals(uname) && !"".equals(pass)) {
DatabaseFunctionality db = new DatabaseFunctionality(LoginActivity.this,0);
db.execute(uname,pass);
if(db.resp.equals("user exist")) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(),"Username or Password is incorrect",Toast.LENGTH_LONG).show();
username.setText(null);
password.setText(null);
}
}
else {
Toast.makeText(getApplicationContext(), "Please Enter Username or Password", Toast.LENGTH_LONG).show();
username.setText(null);
password.setText(null);
}
}
});
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
startActivity(intent);
}
});
}
}
public class SignupActivity extends AppCompatActivity {
public int PICK_IMAGE_REQUEST = 1;
public Bitmap bitmap;
public Uri filePath;
String imgname;
EditText username, password, ownername, cnic, shopname, shopadd, shopphone, shopphone2, mobile;
TextView cpic, ppic;
Spinner citymenu, areamenu;
Button signup2, ucpic, uppic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
ownername = (EditText) findViewById(R.id.rname);
shopname = (EditText) findViewById(R.id.shopname);
shopadd = (EditText) findViewById(R.id.shopadd);
shopphone = (EditText) findViewById(R.id.shopphone);
shopphone2 = (EditText) findViewById(R.id.shopphone2);
mobile = (EditText) findViewById(R.id.mobile);
citymenu =(Spinner) findViewById(R.id.citymenu);
areamenu = (Spinner) findViewById(R.id.areamenu);
cpic = (TextView) findViewById(R.id.coverpic);
ppic = (TextView) findViewById(R.id.profpic);
signup2 = (Button) findViewById(R.id.signup2);
ucpic = (Button) findViewById(R.id.uploadcpicb);
uppic = (Button) findViewById(R.id.uploadppicb);
ucpic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
imgname = getStringImage(bitmap);
cpic.setText(imgname);
}
});
uppic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
imgname = getStringImage(bitmap);
ppic.setText(imgname);
}
});
signup2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String uname = username.getText().toString();
String pass = password.getText().toString();
String rname = ownername.getText().toString();
String city = citymenu.getSelectedItem().toString();
String mnum = mobile.getText().toString();
String sname = shopname.getText().toString();
String area = areamenu.getSelectedItem().toString();
String sadd = shopadd.getText().toString();
String snum1 = shopphone.getText().toString();
String snum2 = shopphone2.getText().toString();
if(!"".equals(rname) && !"".equals(city) && !"".equals(uname) && !"".equals(pass) && !"".equals(sname) && !"".equals(mnum) && !"".equals(area) && !"".equals(sadd) && !"".equals(snum1)) {
DatabaseFunctionality db = new DatabaseFunctionality(SignupActivity.this, 1);
db.execute(rname,uname,pass,city,mnum,sname,area,sadd,snum1,snum2);
if(db.resp.equals("Signup Successful")) {
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
startActivity(intent);
Toast.makeText(SignupActivity.this, "Signup Successful!",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(),"Fields with * are must",Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(getApplicationContext(),"Fields with * are must",Toast.LENGTH_LONG).show();
}
}
});
String[] items = new String[]{"*Select","Abbottabad",
"Adezai",
"Ali Bandar",
"Amir Chah",
/* snip */
"Wazirabad",
"Yakmach",
"Zhob",
"Other"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
citymenu.setAdapter(adapter);
String[] items2 = new String[]{"*Select","Johar Town","Faisal Town", "Main Boulevard","Cantt","Model Town"};
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items2);
areamenu.setAdapter(adapter2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
}

Related

Android Studio org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

I'm trying to post some data using volley to a server.
The issue seems to with an encoded string image.
On this line
String name = namefield.getText().toString();
String age = agefield.getText().toString();
String gender = genderfield.getText().toString();
String color = colorfield.getText().toString();
String notes = notesfield.getText().toString();
String images = encodeImage(bitmap);
updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), images);
if I change image to empty string
updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), "");
then than the data sends to server, which is how I know the image is the problem.
I logged the image response and this is what I get:
Strings: /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAUAAk8DASIA
AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3
ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm
p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA
AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx
BhJBUQdhcRMiMoEIFEKRob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ttdIUeH9A1658Py5twhL+DoZA
yAfEifwPBXxB/wAF3f2U9B/Yk/4J4f8ABDn9huLxBc+Ivg78O/2wPAXgr4la9eLDpum+LNRJn1jW
tZ1qONtqxzHXfHM0ZbDojudqvH5VeifsXf8ABGf/AIOKP2B7D4myfs//ALX3/BOa18V/F7xXqPjL
4mfE/wAceFPin8RPi1441WSSWTGu+OPEn7P7+ILi3eWSSYWyMoS4lMrSedtdv2
while the other data response are normal like:
Strings: red
The logcat says the problem is here:
try {
JSONObject jsonObject = new JSONObject(result);
Log.i("Check", result);
Here's the relevant code:
public void updatedetails(final String name, final String age, final String gender, final String color, final String notes, final String owner, final String id, final String pet_image) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Updating pet details");
progressDialog.show();
try {
String url = "https://happy-paws.co.za/dogwalking/apis/v1/pet/update_pet.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
String result = response.toString();
// Log.d("zzzz","res "+result);
Toast.makeText(update.this, response, Toast.LENGTH_SHORT).show();
getDataResponse1(result);
Log.i("Check", result);
Log.i("Check", response);
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(update.this, error.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("TAG", error.getMessage());
}
}) {
#Override
public byte[] getBody() throws com.android.volley.AuthFailureError {
String str = "{\"name\":\"" + name + "\",\"age\":\"" + age + "\",\"gender\":\"" + gender + "\",\"color\":\"" + color + "\",\"notes\":\"" + notes + "\",\"owner\":\"" + owner + "\",\"id\":\"" + id + "\",\"pet_image\":\"" + pet_image + "\"}";
return str.getBytes();
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
// params.put("email",email);
// params.put("password",password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
} catch (Exception e) {
//App.handleUncaughtException(e);
}
progressDialog.dismiss();
}
public void getDataResponse1(String result) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Please Wait.....");
progressDialog.show();
try {
JSONObject jsonObject = new JSONObject(result);
Log.i("Check", result);
JSONObject current = jsonObject.getJSONObject(result);
String message = current.getString("message");
String name = jsonObject.isNull("name") ? null : jsonObject.getString("name");
String age = jsonObject.isNull("age") ? null : jsonObject.getString("age");
String gender = jsonObject.isNull("gender") ? null : jsonObject.getString("gender");
String notes = jsonObject.isNull("notes") ? null : jsonObject.getString("notes");
String color = jsonObject.isNull("color") ? null : jsonObject.getString("color");
// String android_status=jsonObject.getString("android_status");
if (message.equals("Pet was updated.")) {
Toast.makeText(this, "" + message, Toast.LENGTH_SHORT).show();
// updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), pet_image);
} else {
Toast.makeText(this, "" + message, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
private void selectImage(Context context) {
final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose your profile picture");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent takePicture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
} else if (options[item].equals("Choose from Gallery")) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK && data != null) {
bitmap = (Bitmap) data.getExtras().get("data");
profilepic.setImageBitmap(bitmap);
encodeImage(bitmap);
}
break;
case 1:
if (resultCode == RESULT_OK) {
bitmap = (Bitmap) data.getExtras().get("data");
Uri selectedImage = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(selectedImage);
bitmap = BitmapFactory.decodeStream(inputStream);
profilepic.setImageBitmap(bitmap);
encodeImage(bitmap);
// Glide.clear(profilepic);
} catch (FileNotFoundException e) {
Toast.makeText(update.this, "Pet added succesfully", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
}
public String encodeImage(Bitmap bitmap) {
ByteArrayOutputStream ba = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ba);
byte[] imagebyte = ba.toByteArray();
encode = android.util.Base64.encodeToString(imagebyte, Base64.DEFAULT);
return encode;
}
And then where I submit:
updatebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = namefield.getText().toString();
String age = agefield.getText().toString();
String gender = genderfield.getText().toString();
String color = colorfield.getText().toString();
String notes = notesfield.getText().toString();
String images = encodeImage(bitmap);
updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), images);
Log.d("Strings",images );
Log.d("Strings",color );
image response is ok. you must set image data type as LONGTEXT or LONGBLOB on database server. but a better solution is to use Multipart Image Upload for upload image on server.
you can try with Uploading Images to Server android

Registering with a new account failed

Below is a registration form where user can register a new account, however when I try to sign up it connect to the server, but for some reason it failed to register!
with message from php file (Hmmm Look Like User Already Exist...) however I'm sure that the user doesn't exist in the database table!
RegisterActivity.java
public class RegisterActivity extends AppCompatActivity {
TextView sign_in_text;
EditText Name,Email,Pass,ConPass;
Button reg_button;
AlertDialog.Builder mBuilder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
sign_in_text = (TextView) findViewById(R.id.sign_in);
sign_in_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
}
});
Name = (EditText) findViewById(R.id.user_name);
Email = (EditText) findViewById(R.id.email_register);
Pass = (EditText) findViewById(R.id.password_register);
ConPass = (EditText) findViewById(R.id.password_conf);
reg_button = (Button) findViewById(R.id.reg_button);
reg_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(Name.getText().toString().equals("")|| Email.getText().toString().equals("")|| Pass.getText().toString().equals("")){
mBuilder = new AlertDialog.Builder(RegisterActivity.this);
mBuilder.setTitle("Oops something went wrong!");
mBuilder.setMessage("Please fill all the fields");
mBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = mBuilder.create();
alertDialog.show();
}
else if (!(Pass.getText().toString().equals(ConPass.getText().toString()))){
mBuilder = new AlertDialog.Builder(RegisterActivity.this);
mBuilder.setTitle("Oops something went wrong!");
mBuilder.setMessage("Your passwords are not matching");
mBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
Pass.setText("");
ConPass.setText("");
}
});
AlertDialog alertDialog = mBuilder.create();
alertDialog.show();
}
else {
BackgroundTask backgroundTask = new BackgroundTask(RegisterActivity.this);
backgroundTask.execute("register",Name.getText().toString(),Email.getText().toString(),Pass.getText().toString());
}
}
});
}
}
And this is the background task where I connect the to server
BackgroundTask.java
public class BackgroundTask extends AsyncTask<String, String, String> {
String register_url ="http://justawesome.net/ozone_registration/register.php";
String login_url ="http://justawesome.net/ozone_registration/login.php";
Context ctx;
ProgressDialog mProgressDialog;
Activity activity;
AlertDialog.Builder mBuilder;
public BackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity) ctx;
}
#Override
protected void onPreExecute() {
mBuilder = new AlertDialog.Builder(activity);
mProgressDialog = new ProgressDialog(ctx);
mProgressDialog.setTitle("Please wait");
mProgressDialog.setMessage("Connecting to server....");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String method = params[0];
if (method.equals("register")){
try {
URL url = new URL(register_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter =new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String name = params[1];
String email = params[2];
String password = params[3];
String data = URLEncoder.encode("name", "UTF-8")+"-"+URLEncoder.encode(name,"UTF-8")+"&"+
URLEncoder.encode("email", "UTF-8")+"-"+URLEncoder.encode(email,"UTF-8")+"&"+
URLEncoder.encode("password", "UTF-8")+"-"+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line=bufferedReader.readLine()) != null){
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
Thread.sleep(5000);
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if (method.equals("login")){
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter =new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String email,password;
email = params[1];
password = params[2];
String data = URLEncoder.encode("email", "UTF-8")+"-"+URLEncoder.encode(email,"UTF-8")+"&"+
URLEncoder.encode("password", "UTF-8")+"-"+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line=bufferedReader.readLine()) != null){
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
Thread.sleep(5000);
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String json) {
mProgressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
//JSONObject jsonObject = new JSONObject(json);
//String response = jsonObject.getString("server_response");
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
//JSONArray jsonArray = new JSONArray(response);
JSONObject Jo = jsonArray.getJSONObject(0);
String code = Jo.getString("code");
Log.d("code0", code);
String message = Jo.getString("message");
Log.d("message", message);
if(code.equals("reg_true")){
showDialog("Registration Success", message,code);
Log.d("code1", code);
}
else if(code.equals("reg_false")){
showDialog("Registration Failed", message,code);
Log.d("code2", code);
}
else if (code.equals("login_true")){
Intent intent = new Intent(activity, AccountActivity.class );
intent.putExtra("message", message);
activity.startActivity(intent);
}
else if (code.equals("login_false")){
showDialog("Login Error...",message,code);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
And this is the php file.
P.S.: I tested the backend and it works fine.
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
require "init.php";
$query = "SELECT * FROM userdb WHERE email like '$email';";
$result = mysqli_query($con,$query);
if (mysqli_num_rows($result)>0){
$response = array();
$code = "reg_false";
$message = "Hmmm Look Like User Already Exist...";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
else{
$query = "INSERT INTO userdb(name,email,password)values('$name','$email','$password');";
$result = mysqli_query($con,$query);
if(!$result){
$response = array();
$code = "reg_false";
$message = "Some server error occourred. Try again... ";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}else{
$response = array();
$code = "reg_true";
$message = "Yuoohooo Registration Success... Thank you";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
}
mysqli_close($con);
?>
Appreciate your help

API Not Searching Food Database When Clicking The Search Button get error Permission denied

Hey Guys I'm working on a calorie app where the user clicks the search button and it supposed to retrieve information from the USDA Food Composition Databases API. For some reason it doesnt do anything and I noticed I get an error in the Logcat.
Im new to Android and to API. Thanks again in advance..
logcat :
Here is the logcat Error I'm Getting
AddEntry.java
public class AddEntry extends Fragment implements View.OnClickListener {
EditText FoodET,CalorieET;
ImageButton Savebtn, Cancelbtn;
Button searchbutton;
String foodET,calorieET;
//database
private DatabaseHandler dba;
public AddEntry() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_add_entry, container,
false);
Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
Savebtn.setBackgroundColor(Color.TRANSPARENT);
Savebtn.setOnClickListener(this);
searchbutton = (Button) myView.findViewById(R.id.SearchButton);
searchbutton.setOnClickListener(this);
Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
Cancelbtn.setBackgroundColor(Color.TRANSPARENT);
Cancelbtn.setOnClickListener(this);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
FoodET= (EditText)view.findViewById(R.id.foodEditText);
FoodET.setInputType(InputType.TYPE_CLASS_TEXT);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
CalorieET.setInputType(InputType.TYPE_CLASS_NUMBER);
foodET = ((EditText)
view.findViewById(R.id.foodEditText)).getText().toString();
calorieET = ((EditText)
view.findViewById(R.id.caloriesEditText)).getText().toString();
}
public void saveDataToDB (){
Food food = new Food();
String FoodName = FoodET.getText().toString().trim();
String calString = CalorieET.getText().toString().trim();
//convert the claories numbers to text
if (!calString.equals("")) {
int cal = Integer.parseInt(calString);
food.setFoodName(FoodName);
food.setCalories(cal);
//call addFood method from the DatabaseHandler
dba.addFood(food);
dba.close();
//clear the editTexts
FoodET.setText("");
CalorieET.setText("");
//take the user to the next screen
//
((appMain) getActivity()).loadSelection(0);
;
}
else
{
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SearchButton:
InputMethodManager inputManager = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(
getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
FoodSearch search = new FoodSearch(foodET,CalorieET );
search.execute();
break;
case R.id.SaveBtn:
foodET = FoodET.getText().toString();
calorieET=CalorieET.getText().toString();
if (FoodET.getText().toString().equals(null) ||
CalorieET.getText().toString().equals(null)||
CalorieET.getText().toString().equals("")){
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
((appMain) getActivity()).loadSelection(0);
break;
case R.id.CancelBtn:
// EditText descriptionET=
(EditText)getView().findViewById(R.id.foodEditText);
//descriptionET.setText("");
//EditText calorieET=
(EditText)getView().findViewById(R.id.caloriesEditText);
//calorieET.setText("");
((appMain) getActivity()).loadSelection(0);
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
private class FoodSearch extends AsyncTask<Void, Void, String> {
String food;
EditText calories;
FoodSearch(String food, EditText calories){
this.food = food;
this.calories = calories;
}
#Override
protected String doInBackground(Void... params) {
try {
food = food.replaceAll(" ", "%20");
URL url = new URL("http://api.nal.usda.gov/ndb/search/?
format=JSON&q=" + food
+"&max=1&offset=0&sort=r&api_
key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
try {
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();
String result = stringBuilder.toString();
if(result.contains("zero results")) {
String s = "empty";
return s;
}
JSONObject object = (JSONObject) new
JSONTokener(result).nextValue();
JSONObject list = object.getJSONObject("list");
JSONArray items = list.getJSONArray("item");
String item = items.get(0).toString();
int i = item.indexOf("ndbno\":\"") + 8;
int f = item.indexOf("\"", i);
String ndbno = item.substring(i,f);
Log.d("DEBUG", ndbno);
URL url2 = new URL("http://api.nal.usda.gov/ndb/reports/?
ndbno="+ ndbno +"&type=b&format=JSON&api_
key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection2 = (HttpURLConnection)
url2.openConnection();
BufferedReader bufferedReader2 = new BufferedReader(new
InputStreamReader(urlConnection2.getInputStream()));
StringBuilder stringBuilder2 = new StringBuilder();
String line2;
while ((line2 = bufferedReader2.readLine()) != null) {
stringBuilder2.append(line2).append("\n");
}
bufferedReader2.close();
String res = stringBuilder2.toString();
int index = res.indexOf("\"unit\": \"kcal\",") + 46;
int index2 = res.indexOf("\"", index);
String calories = res.substring(index,index2);
urlConnection2.disconnect();
return calories;
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
String s = "empty";
return s;
}
}
protected void onPostExecute(String response) {
if(!response.isEmpty() && !response.equals("empty")) {
calories.setText(response);
} else {
AlertDialog foodNotFound = new
AlertDialog.Builder(getContext()).create();
foodNotFound.setTitle("Error");
foodNotFound.setMessage("Food not found :(");
foodNotFound.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.dismiss();
}
});
}
}
}
}
You Can call the Async task within the same class and SHow alert dialog in the onPost execute section
public class AddEntry extends Fragment implements View.OnClickListener {
EditText DescriptionET,CalorieET; ImageButton Savebtn, Cancelbtn; Button searchbutton; String description , calorieAmt; //database
private DatabaseHandler dba;
public AddEntry() {
// Required empty public constructor
}
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { // Inflate the layout for this fragment View myView = inflater.inflate(R.layout.fragment_add_entry, container, false);
Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
Savebtn.setBackgroundColor(Color.TRANSPARENT);
Savebtn.setOnClickListener(this);
searchbutton = (Button) myView.findViewById(R.id.SearchButton);
searchbutton.setOnClickListener(this);
Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
Cancelbtn.setBackgroundColor(Color.TRANSPARENT);
Cancelbtn.setOnClickListener(this);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
DescriptionET= (EditText)view.findViewById(R.id.foodEditText);
DescriptionET.setInputType(InputType.TYPE_CLASS_TEXT);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
CalorieET.setInputType(InputType.TYPE_CLASS_NUMBER);
//save to database:
}
public void saveDataToDB (){
Food food = new Food();
String name = DescriptionET.getText().toString().trim();
String calString = CalorieET.getText().toString().trim();
//convert the claories numbers to text
if (!calString.equals("")) {
int cal = Integer.parseInt(calString);
food.setFoodName(name);
food.setCalories(cal);
//call addFood method from the DatabaseHandler
dba.addFood(food);
dba.close();
//clear the editTexts
DescriptionET.setText("");
CalorieET.setText("");
//take the user to the next screen
//
((appMain) getActivity()).loadSelection(0);
;
}
else
{
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SearchButton:
InputMethodManager inputManager = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(
getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
FoodSearch search = new FoodSearch(description,CalorieET);
search.execute();
break;
case R.id.SaveBtn:
description = DescriptionET.getText().toString();
calorieAmt=CalorieET.getText().toString();
if (DescriptionET.getText().toString().equals(null) ||
CalorieET.getText().toString().equals(null)||
CalorieET.getText().toString().equals("")){
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
((appMain) getActivity()).loadSelection(0);
break;
case R.id.CancelBtn:
// EditText descriptionET=
(EditText)getView().findViewById(R.id.foodEditText);
//descriptionET.setText("");
//EditText calorieET=
(EditText)getView().findViewById(R.id.caloriesEditText);
//calorieET.setText("");
((appMain) getActivity()).loadSelection(0);
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
private class FoodSearch extends AsyncTask<Void, Void, String>{
String food;
EditText calories;
FoodSearch(String food, EditText calories){
this.food = food;
this.calories = calories;
}
#Override
protected String doInBackground(Void... params) {
try {
food = food.replaceAll(" ", "%20");
URL url = new URL("http://api.nal.usda.gov/ndb/search/?
format=JSON&q=" + food +"&max=1&offset=0&sort=r&api_key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
try {
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();
String result = stringBuilder.toString();
if(result.contains("zero results")) {
String s = "empty";
return s;
}
JSONObject object = (JSONObject) new
JSONTokener(result).nextValue();
JSONObject list = object.getJSONObject("list");
JSONArray items = list.getJSONArray("item");
String item = items.get(0).toString();
int i = item.indexOf("ndbno\":\"") + 8;
int f = item.indexOf("\"", i);
String ndbno = item.substring(i,f);
Log.d("DEBUG", ndbno);
URL url2 = new URL("http://api.nal.usda.gov/ndb/reports/?ndbno="+ ndbno +"&type=b&format=JSON&api_key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection2 = (HttpURLConnection)
url2.openConnection();
BufferedReader bufferedReader2 = new BufferedReader(new
InputStreamReader(urlConnection2.getInputStream()));
StringBuilder stringBuilder2 = new StringBuilder();
String line2;
while ((line2 = bufferedReader2.readLine()) != null) {
stringBuilder2.append(line2).append("\n");
}
bufferedReader2.close();
String res = stringBuilder2.toString();
int index = res.indexOf("\"unit\": \"kcal\",") + 46;
int index2 = res.indexOf("\"", index);
String calories = res.substring(index,index2);
urlConnection2.disconnect();
return calories;
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
String s = "empty";
return s;
}
}
protected void onPostExecute(String response) {
if(!response.isEmpty() && !response.equals("empty")) {
calories.setText(response);
} else {
AlertDialog foodNotFound = new
AlertDialog.Builder(getContext()).create();
foodNotFound.setTitle("Error");
foodNotFound.setMessage("Food not found :(");
foodNotFound.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
}
}

Image taken from camera cannot display in image view android 5.0, but working in android 4.4

This is my activity code, when click on capture picture button, it will load camera from your phone. after i take a picture with camera, the picture will show at the imageView. Then i will click upload image picture button to upload my picture to server. Here the problem i faced, the code works well on all android version 4.4 and below, when i test this code with android 5.0, the picture taken from camera wasn't show on the imageView. I had tried many solution and yet keep fail. Can anyone help me with this? thank you.
Activity code
public class TestUpload extends Activity implements OnItemSelectedListener {
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String IMAGE_DIRECTORY_NAME = "Hello camera";
private Uri fileUri;
private ImageView imgPreview;
private Button btnCapturePicture, btnUploadImage;
private EditText itemname;
private EditText description;
private EditText price;
private EditText contact;
private String randNum, uname;
Random random = new Random();
private static final String _CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
private static final int RANDOM_STR_LENGTH = 12;
private Spinner spinCat, spinLoc;
private String [] Category = {"IT Gadgets","Men Fashion","Women Fashion","Beauty","Sports","Cars and Motors","Furnitures","Music Instrument","Books","Property","Photography","Games and Toys","kids and Baby","Others"};
private String [] Location = {"Kuala Lumpur","Melacca","Johor","Selangor","Kelantan","Kedah","Negeri Sembilan",
"Pahang","Perak","Perlis","Penang","Sabah","Sarawak","Terengganu"};
private static final String TAG_SUCCESS = "success";
JSONParser2 jsonParser2 = new JSONParser2();
private static String url_create_image = "http://gemini888.tk/GP_trade_api_v2/image_connect/create_product.php";
private SweetAlertDialog pDialog;
long totalSize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload_test);
ActionBar ab = getActionBar();
ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#96ead7")));
ab.setDisplayHomeAsUpEnabled(true);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
btnCapturePicture = (Button) findViewById(R.id.btn_camera);
btnUploadImage = (Button) findViewById(R.id.btn_upload);
itemname = (EditText) findViewById(R.id.input_upload_item_name);
description = (EditText) findViewById(R.id.input_item_desc);
price = (EditText) findViewById(R.id.upload_input_item_price);
contact = (EditText) findViewById(R.id.input_contact);
spinCat = (Spinner) findViewById(R.id.spin_category);
spinLoc = (Spinner) findViewById(R.id.spin_location);
ArrayAdapter<String> adapter_Category = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item, Category);
ArrayAdapter<String> adapter_Location = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item, Location);
adapter_Category.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter_Location.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinCat.setAdapter(adapter_Category);
spinLoc.setAdapter(adapter_Location);
spinCat.setOnItemSelectedListener(this);
spinLoc.setOnItemSelectedListener(this);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String, String> user = new HashMap<String, String>();
user = db.getUserDetails();
uname = user.get("uname");
//timeStamp = new SimpleDateFormat ("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
randNum = getRandomString();
//capture image button click event
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//capture image
captureImage();
}
});
btnUploadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//uploading the file to server
new UploadFileToServer().execute();
}
});
}
//capturing Camera image will lunch camera app request image capture
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
//Start image capture intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
//Receiving activity result method will be called after closing the camera
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//if the result i capture image
if(requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
//success capture image, display it on imageview
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
//user cancel image capture
Toast.makeText(getApplicationContext(), "User cancelled image capture", Toast.LENGTH_SHORT).show();
} else {
//failed to capture image
Toast.makeText(getApplicationContext(), "Sorry, failed to capture image", Toast.LENGTH_SHORT).show();
}
}
}
//Display image from a path to imageview
private void previewCapturedImage() {
imgPreview.setVisibility(View.VISIBLE);
//bitmap factory
BitmapFactory.Options options = new BitmapFactory.Options();
//downsize image as it throws Outofmemory execption for larger images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
imgPreview.setImageBitmap(bitmap);
}
//store the file url as it will be null after returning from camera app
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//save file url in bundle as it will be null on screen orientation change
outState.putParcelable("file_uri", fileUri);
}
//restore the fileUri again
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//get the Urifile
fileUri = savedInstanceState.getParcelable("file_uri");
}
//create file Uri to store image
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
//returning image
private File getOutputMediaFile(int type) {
//External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), UserFunctions.IMAGE_DIRECTORY_NAME);
//create the storage directory if it does not exist
if(!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Failed create" + UserFunctions.IMAGE_DIRECTORY_NAME + "directory");
return null;
}
}
//Create a media file name
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator + uname + randNum + ".jpg");
} else {
return null;
}
return mediaFile;
}
//upload image to server
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new SweetAlertDialog(TestUpload.this, SweetAlertDialog.PROGRESS_TYPE);
pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
pDialog.setTitleText("Picture uploading, please wait..");
//pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(Void...params) {
String iname = itemname.getText().toString();
String des = description.getText().toString();
String iprice = price.getText().toString();
String icontact = contact.getText().toString();
String cat = spinCat.getSelectedItem().toString();
String loc = spinLoc.getSelectedItem().toString();
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("name", iname));
param.add(new BasicNameValuePair("description", des));
param.add(new BasicNameValuePair("price", iprice));
param.add(new BasicNameValuePair("username", uname));
param.add(new BasicNameValuePair("category", cat));
param.add(new BasicNameValuePair("location", loc));
param.add(new BasicNameValuePair("timestamp", randNum));
param.add(new BasicNameValuePair("contact", icontact));
JSONObject json = jsonParser2.makeHttpRequest(url_create_image,
"POST", param);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Log.d("Create Response", "success");
} else {
// failed to create product
Toast.makeText(getApplicationContext(),"failed",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return uploadFile();
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
super.onPostExecute(result);
}
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(UserFunctions.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
setProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(fileUri.getPath());
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("http://gemini888.tk"));
entity.addPart("email", new StringBody("thegemini888#gmail.com"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
public String getRandomString() {
StringBuffer randStr = new StringBuffer();
for (int i =0; i<RANDOM_STR_LENGTH; i++) {
int number = getRandomNumber();
char ch = _CHAR.charAt(number);
randStr.append(ch);
}
return randStr.toString();
}
private int getRandomNumber() {
int randomInt = 0;
randomInt = random.nextInt(_CHAR.length());
if (randomInt - 1 == -1) {
return randomInt;
} else {
return randomInt - 1;
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
spinCat.setSelection(position);
String CatList = (String) spinCat.getSelectedItem();
CatList.toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; go home
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
in captureImage() method try this.
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
//Start image capture intent
}
//first of all create a directory to store your captured Images
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/PGallery");
if (!myDir.exists()) {
myDir.mkdirs();
}
//Give name to your captured Image
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss",java.util.Locale.getDefault());
Date date = new Date();
String sDate = formatter.format(date);
imageName = "PRAVA"+sDate+".jpg";
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
filePath = new File(myDir,imageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(filePath));
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
catch (ActivityNotFoundException e) {
String errorMessage = "Whoops - your device doesn't support capturing images!";
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
On Actvity Result:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
ImagePath = filePath.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(ImagePath, bitmapOptions);
ImageView mImageView = (ImageView) findViewById(R.id.ivCamreaPic);
mImageView.setImageBitmap(bitmap);
}

android java run activity without restarting it

I created simple application which would login to DB and get data from it. But now I found a problem: If you in the first time write wrong login data and try to login second time it won't work. You have to restart it.
I think there is a problem in this code: EDITED
public class MyMoodleApplicationActivity extends Activity {
/** Called when the activity is first created. */
EditText username;
EditText password;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
username = (EditText)findViewById(R.id.username);
password = (EditText)findViewById(R.id.password);
final Button loginButton = (Button)findViewById(R.id.login);
loginButton.setOnClickListener(loginListener);
final Button clearButton = (Button)findViewById(R.id.clear);
clearButton.setOnClickListener(clearListener);
}
private OnClickListener loginListener = new OnClickListener(){
public void onClick(View v){
String usr = username.getText().toString();
String psw = password.getText().toString();
System.out.println("Username: "+usr);
System.out.println("Password: "+psw);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("usern",""+usr));
nameValuePairs.add(new BasicNameValuePair("passw",""+psw));
InputStream is = null;
String result = "";
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://ik.su.lt/*****");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
String usernameFromDB = "";
String firstnameFromDB = "";
String lastnameFromDB = "";
String emailFromDB = "";
String phoneFromDB = "";
String skypeFromDB = "";
String cityFromDB = "";
String descriptionFromDB = "";
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
usernameFromDB = json_data.getString("username");
firstnameFromDB = json_data.getString("firstname");
lastnameFromDB = json_data.getString("lastname");
emailFromDB = json_data.getString("email");
phoneFromDB = json_data.getString("phone1");
skypeFromDB = json_data.getString("skype");
cityFromDB = json_data.getString("city");
descriptionFromDB = json_data.getString("description");
System.out.println(usernameFromDB+ " " + firstnameFromDB+" "+lastnameFromDB+" "
+ emailFromDB + " " + phoneFromDB +" " + skypeFromDB+ " " + cityFromDB + " "+
descriptionFromDB);
}
}
catch(JSONException e){
AlertDialog alertDialog = new AlertDialog.Builder(MyMoodleApplicationActivity.this).create();
alertDialog.setTitle("Klaida!");
alertDialog.setMessage("Toks vartotojas neegzistuoja");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
return;
}
});
alertDialog.show();
Log.e("log_tag", "Error parsing data "+e.toString());
}
if(usr.length()== 0){
AlertDialog alertDialog = new AlertDialog.Builder(MyMoodleApplicationActivity.this).create();
alertDialog.setTitle("Klaida!");
alertDialog.setMessage("Jūs neįvedėte slapyvardžio");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
return;
}
});
alertDialog.show();
}
else if(psw.length()==0){
AlertDialog alertDialog = new AlertDialog.Builder(MyMoodleApplicationActivity.this).create();
alertDialog.setTitle("Klaida!");
alertDialog.setMessage("Jūs neįvedėte slaptažodžio");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
return;
}
});
alertDialog.show();
}
else if (usr.equals(usernameFromDB)){
Intent in = new Intent(getApplicationContext(), LoggedUser.class);
in.putExtra("firstname", firstnameFromDB);
in.putExtra("lastname", lastnameFromDB);
in.putExtra("email", emailFromDB);
in.putExtra("phone1", phoneFromDB);
in.putExtra("skype", skypeFromDB);
in.putExtra("city", cityFromDB);
in.putExtra("description", descriptionFromDB);
startActivity(in);
finish();
}
}};
private OnClickListener clearListener = new OnClickListener(){
#Override
public void onClick(View v){
username.setText("");
password.setText("");
}
};
In these if statements I check if username and password you enter is empty username is not equal to the one in database.
How to rewrite the code that it would work?
Edited:
I have user john in DB but if I write John in login field and press login button it won't say that there is not the John user. And in LogCat I see that json stream is readed. Is there a way to set up a rule that upercase and lowercase letters would be different?

Categories

Resources