I am creating an Android app that can able to delete data from JSON using HTTP DELETE.But I am facing problem. I have created 2 different files. One of MainActivity and Other one of Async.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
onClickButtonListner();
}
public void onClickButtonListner() {
final Button btn = (Button) findViewById(R.id.delete_btn);
final String URL = myurl;
btnDelete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Async asyn = new Async(URL);
asyn.execute();
}
});
}
}
Async.java
public class Async extends AsyncTask<Void, Void, String> {
String murl;
public Async(String url) {
murl = url;
}
#Override
protected String doInBackground(Void... params) {
HttpURLConnection httpURLConnection;
URL url ;
try {
final EditText id= (EditText)findViewById(R.id.delete_id);
**showing unable to resolve method findViewById**
String delete_url = murl + "/" + id.getText().toString();
url = new URL(delete_url);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestMethod("DELETE");
httpURLConnection.connect();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
So my problem is that my Async class is showing Unable to find findViewById method.
So please help me how to solve this problem
Thank you
Try to change your code as below:
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
onClickButtonListner();
}
public void onClickButtonListner() {
final Button btn = (Button) findViewById(R.id.delete_btn);
final String URL = myurl;
final EditText id= (EditText)findViewById(R.id.delete_id);
btnDelete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Async asyn = new Async(URL,id.getText().toString());
asyn.execute();
}
});
}
}
Async.java
public class Async extends AsyncTask<Void, Void, String> {
String murl,id;
public Async(String url,String _id) {
murl = url;
id=_id;
}
#Override
protected String doInBackground(Void... params) {
HttpURLConnection httpURLConnection;
URL url ;
try {
String delete_url = murl + "/" + id;
url = new URL(delete_url);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestMethod("DELETE");
httpURLConnection.connect();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
Related
im new with Android Studio, and I want to connect Android Studio, to a database created in another compiler. When I execute the debugger and reach de line "BufferedReader bf = new BufferedReader(new InputStreamReader(conn.getInputStream()));", I get and Exception call "FileNotFoundException".
Can someone help me?
Thank you very much.
public class Menu_Login extends AppCompatActivity {
EditText usuario, password;
Button login;
String url_login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_login);
usuario = (EditText) findViewById(R.id.escribir_nombre); // COMO DECLARAR UN EDIT TEXT
password = (EditText) findViewById(R.id.escribir_contraseƱa);
login = (Button) findViewById(R.id.click_boton);
final Context context = this;
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String user = usuario.getText().toString();
String pass = password.getText().toString();
url_login = String.format("http://192.168.1.35/loguear?nombre=%s&password=%s",user,pass);
new MultiplyTask(context).execute(user);
}
});
}
public class MultiplyTask extends AsyncTask <String,Void,String>
{
Context context;
private MultiplyTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String value) {
TextView n = (TextView) findViewById (R.id.mostrar_resultado);
n.setText(value);
}
#Override
protected String doInBackground(String... params) {
try
{
URL url = new URL(url_login);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 );
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
BufferedReader bf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
int status = conn.getResponseCode();
InputStream error = conn.getErrorStream();
String value = bf.readLine();
return value;
}
catch (Exception e)
{
System.out.println(e);
e.printStackTrace();
}
return null;
}
}
}
My Activity Code: Note this is not my main activity, right now i am using a button to fetch images from the database but instead I need to fetch all the images when the app load.
public class QuotesPictures extends Activity implements View.OnClickListener {
private String imagesJSON;
private static final String JSON_ARRAY = "result";
private static final String IMAGE_URL = "url";
private JSONArray arrayImages = null;
private int TRACK = 0;
private Button buttonMoveNext;
private Button buttonMovePrevious;
private ImageView imageView;
private static final String IMAGES_URL = "http://stressreliefapp.esy.es/getAllImages.php";
private Button buttonFetchImages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes_pictures);
//Defining all the buttons
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
}
//Using AsyncTask to load the data in the background thread and then publishing on the UI thread
private void getImage(String urlToImage) {
class GetImage extends AsyncTask<String, Void, Bitmap> {
ProgressDialog loading;
#Override
protected Bitmap doInBackground(String... params) {
URL url = null;
Bitmap image = null;
String urlToImage = params[0];
try {
url = new URL(urlToImage);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(QuotesPictures.this, "Loading Images...", "Please wait...", true, true);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
loading.dismiss();
imageView.setImageBitmap(bitmap);
}
}
GetImage gi = new GetImage();
gi.execute(urlToImage);
}
// Method used to get all the images from the database using AsyncTask
public void getAllImages() {
class GetAllImages extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(QuotesPictures.this, "Loading Images...", "Please wait...", true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
imagesJSON = s;
extractJSON();
showImage();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetAllImages gai = new GetAllImages();
gai.execute(IMAGES_URL);
}
private void extractJSON() {
try {
JSONObject jsonObject = new JSONObject(imagesJSON);
arrayImages = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showImage() {
try {
JSONObject jsonObject = arrayImages.getJSONObject(TRACK);
getImage(jsonObject.getString(IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext() {
if (TRACK < arrayImages.length()) {
TRACK++;
showImage();
}
}
private void movePrevious() {
if (TRACK > 0) {
TRACK--;
showImage();
}
}
#Override
public void onClick(View v) {
if (v == buttonFetchImages) {
getAllImages();
}
if (v == buttonMoveNext) {
moveNext();
}
if (v == buttonMovePrevious) {
movePrevious();
}
}
}
Just execute your download method in onCreate method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes_pictures);
//Defining all the buttons
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
getImage("your image url");
}
Move your code at onclicklistener to onResume.
public void onResume()
{
super.onResume();
/* your code at OnClickListener */
}
I tried almost all the solution but there's some problem with my Inner AsyncTask class. It seems that doInBackground() is not being executed.
onPreExecute() and onPostExecute()are working. However, doInBackground() does not read the code.
I'm really sure about getJSON() is correct 100% because i used the same code before
this is my class
public class My extends Activity implements Runnable {
public static String s = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
findViewById(android.R.id.content).postDelayed(this, 3000);
getJSON("My link ");
}
#Override
public void run() {
startActivity(new Intent(SplashActivity.this, MainActivity.class));
finish();
}
}
AsyncTask:
private void getJSON(String url) {
class GetJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
s = sb.toString().trim();
return sb.toString().trim();
} catch(Exception e){
return null;
}
}
#Override
protected void onPostExecute(String ss) {
super.onPostExecute(ss);
s = ss;
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}
Thanks
I'm working on a login and registration activity using php mysql in Android. I tried testing the registration part but it's not working. My php files have been tested and they're working fine. I suspected my problem might be the url I've provided, but it works in the browser. When the details are entered in the registration form, clicking submit button does nothing.
Here's my code:
Login.java
public class Login extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public void userLogin(View view)
{
}
public void userReg(View view)
{
startActivity(new Intent(this, Registration.class));
}
}
Registration.java
public class Registration extends Activity {
EditText ETname, ETusername, ETpassword;
String name, username, userpass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
ETname = (EditText)findViewById(R.id.newUsername);
ETusername = (EditText)findViewById(R.id.newUserid);
ETpassword = (EditText)findViewById(R.id.newUserpassword);
}
public void reg(View view)
{
name=ETname.getText().toString();
username=ETusername.getText().toString();
userpass=ETpassword.getText().toString();
String method= "register";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method,name,username,userpass);
finish();
}
}
BackgroundTask.java
public class BackgroundTask extends AsyncTask<String, Void, String> {
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx=ctx;
}
#Override
protected String doInBackground(String... params)
{
String reg_url="http://127.0.0.1/webapp/register.php";
String login_url="http://127.0.0.1/webapp/login.php";
String method= params[0];
if(method.equals("register"))
{
String name=params[1];
String user_name=params[2];
String user_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(name,"UTF-8")+"&"+
URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"+
URLEncoder.encode("user_pass","UTF-8")+"="+URLEncoder.encode(user_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 null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();
}
}
you may not need to convert your KEY to encode just value needs to be encoded So,
Change this
String data = URLEncoder.encode("user","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"+
URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"+
URLEncoder.encode("user_pass","UTF-8")+"="+URLEncoder.encode(user_pass,"UTF-8");
To
String data = "user"="+URLEncoder.encode(name,"UTF-8")+"&"+
"user_name"+"="+URLEncoder.encode(user_name,"UTF-8")+"&"+"user_pass"+"="+URLEncoder.encode(user_pass,"UTF-8");
See if this work out for you.
You said you click the submit button, maybe you are not calling the onClick properly.
Have you tried getting a reference to the button in the Activity via findViewById(R.id.button)?
Also try printing the url to make sure it's in the right format.
This is my java code. I have been getting no value for url in my android studio. I intend to get image from sql database at wamp server.
public class MainActivity extends AppCompatActivity implements
View.OnClickListener{
private String imagesJSON;
private static final String JSON_ARRAY ="result";
private static final String IMAGE_URL = "url";
private JSONArray arrayImages= null;
private int TRACK = 0;
private static final String IMAGES_URL =
"http://192.168.43.214/apexStore2/image.php";
private Button buttonFetchImages;
private Button buttonMoveNext;
private Button buttonMovePrevious;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
}
private void extractJSON(){
try {
JSONObject jsonObject = new JSONObject(imagesJSON);
arrayImages = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showImage(){
try {
JSONObject jsonObject = arrayImages.getJSONObject(TRACK);
getImage(jsonObject.getString(IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext(){
if(TRACK < arrayImages.length()){
TRACK++;
showImage();
}
}
private void movePrevious(){
if(TRACK>0){
TRACK--;
showImage();
}
}
private void getAllImages() {
class GetAllImages extends AsyncTask<String,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Fetching
Data...","Please Wait...",true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
imagesJSON = s;
extractJSON();
showImage();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection)
url.openConnection();
con.setRequestProperty("Content-Type",
"application/json;charset=utf-8");
con.setRequestProperty("X-Requested-With",
"XMLHttpRequest");
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new
InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
}
GetAllImages gai = new GetAllImages();
gai.execute(IMAGES_URL);
}
private void getImage(String urlToImage){
class GetImage extends AsyncTask<String,Void,Bitmap>{
ProgressDialog loading;
#Override
protected Bitmap doInBackground(String... params) {
URL url = null;
Bitmap image = null;
String urlToImage = params[4];
try {
url = new URL(urlToImage);
image =
BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Downloading
Image...","Please wait...",true,true);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
loading.dismiss();
imageView.setImageBitmap(bitmap);
}
}
GetImage gi = new GetImage();
gi.execute(urlToImage);
}
#Override
public void onClick(View v) {
if(v == buttonFetchImages) {
getAllImages();
}
if(v == buttonMoveNext){
moveNext();
}
if(v== buttonMovePrevious){
movePrevious();
}
}
This is my php code. When i run my php code, i got the following output:
{
"result": [{
"product_img1": "product-131.jpg"
}, {
"product_img1": "product-124.jpg"
}, {
"product_img1": "product-118.jpg"
}, {
"product_img1": "product-126.jpg"
}, {
"product_img1": "USM_New_Logo1.jpg"
}, {
"product_img1": "UI.PNG"
}, {
"product_img1": "cat402.PNG"
}, {
"product_img1": "launcher.png"
}]
}
My php code got fetch the image from sql database, however, my android studio could not fetch it. Is there any solutions to it?
<?php
include ('classes/functions.php');
$check_product = "SELECT * FROM products WHERE cat_id = '0';";
$run_product_checking = mysqli_query($con, $check_product);
$result = array();
while($row = mysqli_fetch_array($run_product_checking)){
array_push($result,
array('product_img1'=>$row[4]
));
}
echo json_encode(array("result"=>$result));
?>
Change the IP-address into it's Domain-name value.
According to your AsyncTask class, you are passing the url as the first parameter,
class GetImage extends AsyncTask<String,Void,Bitmap>{
.....
}
But here you are receiving it as the 4'th parameter,
String urlToImage = params[4];
To solve this, simply replace the param value from 4 to 0,
String urlToImage = params[0];
PS: Make sure the JSON string " IMAGE_URL " doesn't returns null value,
getImage(jsonObject.getString(IMAGE_URL));