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;
}
}
}
Related
MainActivity.java
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_name = (EditText) findViewById(R.id.user_name);
password = (EditText)findViewById(R.id.password);
submit_btn = (Button) findViewById(R.id.submit);
submit_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Sender s = new Sender(v.getContext(),urlAddress,user_name,password);
s.execute();
cxt = getApplicationContext();
}
});
}
public void GoUserActivity(){
Intent i = new Intent(MainActivity.this,com.example.prakash.cinihive.UserActivity.class);
startActivity(i);
}
}
Sender.java
package com.example.prakash.cinihive;
public class Sender extends AsyncTask<Void,Void,String> {
Context c;
String urlAddress;
EditText user_name,password;
String UserName,Password;
ProgressDialog pd;
MainActivity main = new MainActivity();
public Sender(Context c, String urlAddress, EditText user_name, EditText password) {
this.c = c;
this.urlAddress = urlAddress;
this.user_name = user_name;
this.password = password;
UserName = user_name.getText().toString();
Password = password.getText().toString();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("send");
pd.setMessage("Sending..Please wait");
pd.show();
}
#Override
protected String doInBackground(Void... voids) {
return this.send();
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
pd.dismiss();
if(response !=null){
//Toast.makeText(c,response,Toast.LENGTH_LONG).show();
//Log.d("Response",response);
if(response.equals("false")){
Toast.makeText(c,"Invalid Credentials",Toast.LENGTH_LONG).show();
}
else{
main.GoUserActivity();
//Toast.makeText(c,response,Toast.LENGTH_LONG).show();
}
user_name.setText("");
password.setText("");
}
else{
Toast.makeText(c,"Un succesfullll",Toast.LENGTH_LONG).show();
}
}
public String send(){
HttpURLConnection con = Connector.connect(urlAddress);
//Toast.makeText(c,con.toString(),Toast.LENGTH_LONG).show();
if(con==null){
Toast.makeText(c,"Connection Null",Toast.LENGTH_LONG).show();
return null;
}
try{
// Log.d("Connection status","Connection not null");
OutputStream os = con.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
bw.write(new DataPack(UserName,Password).Packdata());
bw.flush();
bw.close();
os.close();
int responseCode = con.getResponseCode();
Log.d("MYINT","Response Id :"+responseCode);
if(responseCode==con.HTTP_OK){
Log.d("Response code","Response code success");
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer response = new StringBuffer();
String line;
while((line=br.readLine())!=null){
response.append(line);
}
br.close();
return response.toString();
}else{
Log.d("Response code","Failure");
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This is my code My problem was Intent Statement Not working in GoUserActivity funtion
At the same time Intent Statement Working well in OnCreate function.
When I try to run inside GoUserActivity,it will raise the runtime error(NullPoniterException "Intent i = new Intent(MainActivity.this,com.example.prakash.cinihive.UserActivity.class);")
I think you'll find things work better if you move your AsyncTask inside MainActivity as an inner class. You'll be able to call GoUserActivity() without having to new another instance of MainActivity, which you should never do.
The code below is for the login authentication of the app I'm working on:
public class Login extends AppCompatActivity implements View.OnClickListener{
private EditText inputemail;
private EditText inputpassword;
private Button btnlogin;
private static final String LOGIN_URL = "http://wwww.example.com/foodify/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputemail = (EditText)findViewById(R.id.input_email);
inputpassword = (EditText)findViewById(R.id.input_password);
btnlogin = (Button)findViewById(R.id.btn_login);
btnlogin.setOnClickListener(this);
Button aboutapp = (Button)findViewById(R.id.learnmore);
aboutapp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent learnmore = new Intent(Login.this, AboutApp.class);
startActivity(learnmore);
}
});
Button signup = (Button)findViewById(R.id.signupnow);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent signup = new Intent(Login.this, SignUp.class);
startActivity(signup);
}
});
Button ccode = (Button)findViewById(R.id.ccodebtn);
ccode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ccode = new Intent(Login.this, Confirmation_Sign_Up.class);
startActivity(ccode);
}
});
btnlogin.setOnClickListener(this);
}
#Override
public void onClick(View v){
if(v == btnlogin){
LoginUser();
}
}
private void LoginUser() {
String email = inputemail.getText().toString();
String password = inputpassword.getText().toString();
login(email,password);
}
private void login(String email, String password) {
String urlSuffix = "?email="+email+"&password="+password;
class LoginUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Login.this, "Please Wait","Authenticating...", true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
if (s.matches("Login successful")) {
Intent regcom = new Intent();
regcom.setClass(getApplicationContext(), main_menu.class);
startActivity(regcom);
}
}
#Override
protected String doInBackground(String... params) {
String s = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(LOGIN_URL+s);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
result = bufferedReader.readLine();
return result;
}catch(Exception e){
return null;
}
}
}
LoginUser ru = new LoginUser();
ru.execute(urlSuffix);
}
}
On pressing the login button, the authenticating ProgressDialog shows but the app crashes at the post_execute stage, according to the logcat
The logcat entry is shown below:
FATAL EXCEPTION: main
Process: mediatech3.foodifyplus, PID: 19099
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean
java.lang.String.matches(java.lang.String)' on a null object reference
at mediatech3.foodifyplus.Login$1LoginUser.onPostExecute(Login.java:95)
at mediatech3.foodifyplus.Login$1LoginUser.onPostExecute(Login.java:81)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.-wrap1(Unknown Source:0)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I have checked the login.php file for errors and found none. I don't really understand what the error refers to and am not sure how to proceed. Any advice would be greatly appreciated. :)
Change the return statement of doInBackground as mentioned below.
#Override
protected String doInBackground(String... params) {
String s = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(LOGIN_URL+s);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
result = bufferedReader.readLine();
return result;
}catch(Exception e){
// return null;
// change this to
e.printStackTrace();
return "Error in login";
}
}
Printing the exception will be a good idea to check whether it is failing somewhere else or not.
I making a quiz app in which i am displaying question and it's four option in radio buttons,i want to display question one by one by updating it to the next id question on a click of button.....How should i do that? and also how should i check score for it which i want to display on the next activity i will make? the app crashes on the listner of button
Thanks in advance!
QuizActivity:
public class Quiz extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton optionOne,optionTwo,optionThree,optionFour;
private TextView questionName;
String question_name;
String option1,option2,option3,option4;
Button next_question;
int first_question_index=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
questionName=(TextView)findViewById(R.id.question_name);
radioGroup =(RadioGroup)findViewById(R.id.radioGroup);
optionOne=(RadioButton)findViewById(R.id.answerOne);
optionTwo=(RadioButton)findViewById(R.id.answerOne);
optionThree=(RadioButton)findViewById(R.id.answerOne);
optionFour=(RadioButton)findViewById(R.id.answerOne);
next_question=(Button)findViewById(R.id.button_next_question);
FetchLists fetchLists =new FetchLists();
fetchLists.execute(10,0);
next_question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
first_question_index++;
}
}); }
public class FetchLists extends AsyncTask<Integer, Void, String> {
#Override
protected String doInBackground(Integer... params) {
String urlString = "http://aptronnoida.com/Aditya_July4/Demo/JAVA_FETCH.php";
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line = reader.readLine();
String response = "";
while (line != null) {
response += line;
line = reader.readLine();
}
JSONObject object = new JSONObject(response);
JSONArray jsonArray = object.getJSONArray("data");
JSONObject list = (JSONObject) jsonArray.get(first_question_index);
question_name= list.getString("Question");
option1=list.getString("A1");
option2=list.getString("A2");
option3=list.getString("A3");
option4=list.getString("A4");
} catch (Exception e) {
e.printStackTrace();
}
return "quiz";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
questionName.setText(question_name);
((RadioButton) radioGroup.getChildAt(0)).setText(option1);
((RadioButton) radioGroup.getChildAt(1)).setText(option2);
((RadioButton) radioGroup.getChildAt(2)).setText(option3);
((RadioButton) radioGroup.getChildAt(3)).setText(option4);
}
}
}
public class Quiz extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton optionOne,optionTwo,optionThree,optionFour;
private TextView questionName;
String question_name;
String option1,option2,option3,option4;
Button next_question;
int first_question_index=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
questionName=(TextView)findViewById(R.id.question_name);
radioGroup =(RadioGroup)findViewById(R.id.radioGroup);
optionOne=(RadioButton)findViewById(R.id.answerOne);
optionTwo=(RadioButton)findViewById(R.id.answerOne);
optionThree=(RadioButton)findViewById(R.id.answerOne);
optionFour=(RadioButton)findViewById(R.id.answerOne);
next_question=(Button)findViewById(R.id.button_next_question);
next_question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
first_question_index++;
FetchLists fetchLists = new FetchLists();
fetchLists.execute(10, 0);
}
});
FetchLists fetchLists = new FetchLists();
fetchLists.execute(10, 0);
}
public class FetchLists extends AsyncTask<Integer, Void, String> {
#Override
protected String doInBackground(Integer... params) {
String urlString = "http://aptronnoida.com/Aditya_July4/Demo/JAVA_FETCH.php";
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line = reader.readLine();
String response = "";
while (line != null) {
response += line;
line = reader.readLine();
}
JSONObject object = new JSONObject(response);
JSONArray jsonArray = object.getJSONArray("data");
JSONObject list = (JSONObject) jsonArray.get(first_question_index);
Log.d("ashu","JsonObject "+list);
question_name= list.getString("Question");
option1=list.getString("A1");
option2=list.getString("A2");
option3=list.getString("A3");
option4=list.getString("A4");
} catch (Exception e) {
e.printStackTrace();
}
return "quiz";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
questionName.setText(question_name);
((RadioButton) radioGroup.getChildAt(0)).setText(option1);
((RadioButton) radioGroup.getChildAt(1)).setText(option2);
((RadioButton) radioGroup.getChildAt(2)).setText(option3);
((RadioButton) radioGroup.getChildAt(3)).setText(option4);
}
}
}
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.
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);
}
}