Everyone i'm getting error while using Intent in android. I have a MainActivity from where i call another class called BackgroundWorker so after doing some functions of login i want to go to user page if it is a sucesss.enter code here im attaching my code here Please help
package com.example.user.mybookapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText UsernameEt, PasswordEt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UsernameEt = (EditText) findViewById(R.id.etusername);
PasswordEt = (EditText) findViewById(R.id.etpassword);
}
public void OnLogin(View view) {
String username = UsernameEt.getText().toString();
String password = PasswordEt.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type,username,password);
}
}
//BackgoundWorker class
package com.example.user.mybookapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by user on 15-09-2016.
*/
public class BackgroundWorker extends AsyncTask<String,Void,String> {
public Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx){
context = ctx;
}
#Override
protected String doInBackground(String[] params)
{
String type = params[0];
String login_url = "http://192.168.4.2/login.php";
if(type.equals("login"))
{
try {
//Context context = getApplicationContext();
//Toast t= Toast.makeText(ctx,"click",Toast.LENGTH_SHORT).show();
//alertDialog = new AlertDialog.Builder(context).create();
//alertDialog.setTitle("login status");
String user_name = params[1];
String password = params[2];
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 post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
+URLEncoder.encode(password,"UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!=null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("login status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
String s=result.trim();
if (s.equalsIgnoreCase("success")){
Intent i =Intent(BackgroundWorker.this,User.class);//Problem
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Intent i =Intent(context,User.class);
This should fix the error, intent should be called using current context.
Intent i =Intent(context,User.class);
context.startActivity(i);
This will work as BackgroundWorker.this is a non activity reference.
Intent intent = new Intent(mContext,SecondClass.class);
intent.putExtra("KEY","Value");
startActivity(intent);
//here KEY = the identifier of specific value
//on other side of SecondClass Activity. catch this data using
String res = getIntent().getStringExtra("KEY");
Intent constructor needs a context as first parameter and you are giving it AsyncTask. You are not constructing object of Intent class properly, in other words you have forgotten to write new keyword.This is the syntax to create a object:-
<Class> <objectName> = new <Class/Subclass>(constructor_params_separated_by_commas);
Intent i =Intent(BackgroundWorker.this,User.class);//Problem
change it to
Intent i =new Intent(context,User.class);//Problem solved
context.startActivity(i);
As mentioned in the answers above, first problem is the inappropriate context, second problem is that you are passing wrong arguments in your background worker class while performing background task execution. Your AsyncTask extension:
AsyncTask<String, Void, String>
shows that you must pass String in doInBackground method, while in the code above you are trying to get string Array although you have passed String parameters from your main activity i.e
protected String doInBackground(String[] params)
should be
protected String doInBackground(String... params)
Hope that solves the issue.
Related
I have many QR codes ex. Example on imgur, which has peoples' names, numbers, and emails, and I need to scan them. The data comes in something like this: "joe,1234567890,joe#joe.com". I want to write an app that uploads the data to a google sheet and I found a tutorial online from crazycodersclub.com, but when I do the same thing it gives me an error, something like:
Exception: Invalid argument: URL (line 11, file "Code")
Google Script Code
function doGet(e){
var url = encodeUrl("https://docs.google.com/spreadsheets/d/1IEAHcv2n33YO9d7IbfWNVLv2Hl1Q1UXveazPcgMZrMs/edit?usp=sharing/")
var ss = SpreadsheetApp.openByUrl(url);
var sheet = ss.getSheetByName("Sheet1");
return insert(e,sheet);
}
function doPost(e){
var url = encodeUrl("https://docs.google.com/spreadsheets/d/1IEAHcv2n33YO9d7IbfWNVLv2Hl1Q1UXveazPcgMZrMs/edit?usp=sharing/")
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1IEAHcv2n33YO9d7IbfWNVLv2Hl1Q1UXveazPcgMZrMs/edit?usp=sharing/");
var sheet = ss.getSheetByName("Sheet1");
return insert(e,sheet);
}
function insert(e,sheet) {
var scannedData = e.parameter.sdata;
var d = new Date();
var ctime = d.toLocaleString();
sheet.appendRow([scannedData,ctime]);
return ContentService
.createTextOutput("Success")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
MainActivity.java
package com.tarbiya.scannerapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
String scannedData;
Button scanBtn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Activity activity =this;
scanBtn = (Button)findViewById(R.id.scan_btn);
scanBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setBeepEnabled(false);
integrator.setCameraId(0);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode,resultCode,data);
if(result!=null) {
scannedData = result.getContents();
if (scannedData != null) {
// Here we need to handle scanned data...
new SendRequest().execute();
}else {
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public class SendRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try{
//Enter script URL Here
URL url = new URL("https://script.google.com/macros/s/AKfycby_G_K-kmm77peQBSY6xmNZjsDcFIkDgqZwxz6e7guyte5Lxe8/exec");
JSONObject postDataParams = new JSONObject();
//int i;
//for(i=1;i<=70;i++)
// String usn = Integer.toString(i);
//Passing scanned code as parameter
postDataParams.put("sdata",scannedData);
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}
If you need to see more code, I can attach some more. It looks basically the same as the one in the tutorial right now.
Thank you so much for your help.
The reason you were receiving the Exception: Invalid argument: URL message is because the url you were passing to the openByUrl was not in the correct format.
If you check the documentation for the openByUrl method here, you can see the accepted format of the link.
https://docs.google.com/spreadsheets/d/abc1234567/edit
In your situation, you will have to remove the part after the /edit.
Reference
Apps Script SpreadsheetApp Class - openByUrl(url).
So I've been cracking my brain with this issues. I'm trying to validate if the an user credentials on a app connected to mysql are valid. The thing is that wherever I try to compare the result of the query with a string all I get is the else statement.
Here's the Fragment for the Login
package com.example.pablorjd.CheckThisOut;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Login extends AppCompatActivity {
EditText etUsername;
EditText etPassword;
Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etUsername = (EditText)findViewById(R.id.etUsername);
etPassword = (EditText)findViewById(R.id.etPassword);
btnLogin = (Button)findViewById(R.id.btnLogin);
}
public void onLogin(View view){
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type,username,password);
}
}
I'm using a background class to make the connection to mysql
package com.example.pablorjd.CheckThisOut;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundWorker extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker(Context ctx){
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://10.20.13.31/checkthisout/login.php";
if (type.equals("login")){
try {
String user_name = params[1];
String password = params[2];
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 post_data = URLEncoder.encode("user_name", "UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
+URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine())!=null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String result) {
if (result.equals("true")){
Toast.makeText(context, "If is working", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,result, Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
I know the DB connections is working because I'm actually receiving the message that I set on the php file.
All I know is that for some reason the if statement is not working for this.
please if someone could shed a light for me that'd be great.
OK so, for some reason, the validation just wouldn't take the string comparison and instead jumped to the else statement showing in this case a Toast. What I had to do was to modify the string given to me by the php file so it would be just a number (0 or 1 in this case). then I parsed the string into an int and the if worked like a charm.
This is the resulting code
#Override
protected void onPostExecute(String result) {
int val = Integer.parseInt(result.replaceAll("[\\D]",""));
if (val == 0){
Intent intent = new Intent(context,MainActivity.class);
context.startActivity(intent);
Toast.makeText(context,"Login exitoso",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,"Login erroneo",Toast.LENGTH_SHORT).show();
}
}
I still don't know why the if statement wouldn't work with strings.
I have this class WelcomeActivity and backgroundLogin which does a login sequence. I have my username and password editbox on the WelcomeActivity and then the login button is pressed I proceeds to the backgroungLogin to connect to the database and then compare the values of the available entries.
WelcomeActivity:
package com.a000webhostapp.cbhtermitecontrol.termitecontrol;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class WelcomeActivity extends AppCompatActivity{
Button loginButton;
EditText userText, codeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
loginButton = (Button) findViewById(R.id.loginButtonXML);
userText = (EditText) findViewById(R.id.userTextXML);
codeText = (EditText) findViewById(R.id.codeTextXML);
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = userText.getText().toString();
String password = codeText.getText().toString();
String type = "login";
backgroundLogin backgroundLogin = new backgroundLogin(WelcomeActivity.this);
backgroundLogin.execute(type, username, password);
}
});
}
public void onLogin(View view){
String username = userText.getText().toString();
String password = codeText.getText().toString();
String type = "login";
backgroundLogin backgroundLogin = new backgroundLogin(this);
backgroundLogin.execute(type, username, password);
}
}
backgroundActivity:
package com.a000webhostapp.cbhtermitecontrol.termitecontrol;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.speech.tts.Voice;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class backgroundLogin extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;
backgroundLogin (Context ctx){
this.context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "https://cbhtermitecontrol.000webhostapp.com/android/loginA2DB.php";
if(type.equals("login"))
try {
String username = params[1];
String password = params[2];
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 post_data = URLEncoder.encode("username", "UTF-8")+"="+URLEncoder.encode(username, "UTF-8")+"&"
+URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line;
while ((line = bufferedReader.readLine())!=null){
result+=line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
There are my code, however when I pressed the login button the onPre/PostExecute seem not working. Looking in the Run App Logs in Android Studio the only feed back I got after pressing the login button is this
D/libc: [NET] android_getaddrinfo_proxy get netid:0
D/libc: [NET] android_getaddrinfo_proxy-, success
Make sure to call
alertDialog.show();
In both onPreExecute and onPostExecute
I am trying to send some data to web database using AsyncTask but it gives me error in this line in preExecute method when i try to initialize progress dialog.
dialog = new ProgressDialog(MainActivity.this, R.style.CustomAlertDialogStyle)
Error about MainActivity.this saying "mainactivity is not an enclosing class".
Here is my full code.
package com.cplusplusapp.rashidfaheem.hybridsoftwaresolutions.hbss.rashidfaheem.webservice;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.HttpURLConnection;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
Spinner sp;
Button signup, login;
EditText edtname, edtemail, edtaddress, edtpassword, edtphone, edtcity;
String name,pass,add,catagory,phone,email,city;
ArrayAdapter<String> adapter;
String[] options = {"Student", "Teacher"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signup = (Button) findViewById(R.id.signup);
login = (Button) findViewById(R.id.login);
edtname = (EditText) findViewById(R.id.edtname);
edtemail = (EditText) findViewById(R.id.edtemail);
edtaddress = (EditText) findViewById(R.id.edtaddress);
edtpassword = (EditText) findViewById(R.id.edtpassword);
edtphone = (EditText) findViewById(R.id.edtphone);
edtcity = (EditText) findViewById(R.id.edtcity);
sp = (Spinner) findViewById(R.id.sp);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, options);
sp.setAdapter(adapter);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String permission="false";
new adduser().execute(edtname.getText().toString(), edtemail.getText().toString(), edtpassword.getText().toString(),
edtcity.getText().toString(), edtphone.getText().toString(), edtaddress.getText().toString(), permission, sp.getSelectedItem().toString());
}
});
}
}
class adduser extends AsyncTask<String, String, String>{
Context mcontext;
ProgressDialog dialog;
HttpURLConnection conn;
URL url=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this, R.style.CustomAlertDialogStyle);
dialog.setMessage("Registering User, Please Wait");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected String doInBackground(String... strings) {
try{
// Enter URL address where your php file resides
url=new URL("http://127.0.0.1/rashid/signup.php");
}catch (MalformedURLException e){
e.printStackTrace();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder();
builder.appendQueryParameter("customer_name", strings[0]);
builder.appendQueryParameter("customer_email", strings[1]);
builder.appendQueryParameter("customer_pass", strings[2]);
builder.appendQueryParameter("customer_city", strings[3]);
builder.appendQueryParameter("customer_contact", strings[4]);
builder.appendQueryParameter("customer_address", strings[5]);
builder.appendQueryParameter("permission", strings[6]);
builder.appendQueryParameter("category", strings[7]);
String query = builder.build().getEncodedQuery();
// Open connection for sending data
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
conn.connect();
} catch (IOException e){
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
try{
int code = conn.getResponseCode();
// Check if successful connection made
if (code== HttpsURLConnection.HTTP_OK){
// Read data sent from server
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line=reader.readLine())!=null){
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessfull");
}
}catch (IOException e){
e.printStackTrace();
return ("Exception");
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
if (result.equalsIgnoreCase("true")){
/* Here launching another activity when login successful. If you persist login state
use sharedPreferences of Android. and logout button to clear sharedPreferences.
*/
Toast.makeText(mcontext, "Registered Successfully", Toast.LENGTH_LONG).show();
} else if (result.equalsIgnoreCase("false")){
// If username and password does not match display a error message
Toast.makeText(mcontext, "Register First", Toast.LENGTH_LONG).show();
} else if (result.equalsIgnoreCase("Exception")|| result.equalsIgnoreCase("Unsuccessful")){
Toast.makeText(mcontext, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();
}
}
}
You are trying to access a class (MainActivity) that is inside it's own file from another class that is in its own file (adduser) . There is no way to do that - how is one class supposed to know about the other's instance magically? What you can do:
Move the AsyncTask so it is an inner class in MainActivity
Pass off your Activity to the AsyncTask (via its constructor) then acess using activityVariable.findViewById(); (I am using mActivity in the example below) Alternatively, your ApplicationContext (use proper naming convention, the A needs to be lowercase) is actually an instance of MainActivity you're good to go, so do ApplicationContext.findViewById();
Using the Constructor example:
public class adduser extends AsyncTask<Context, String, ArrayList<Card>>
{
Context ApplicationContext;
Activity mActivity;
public adduser (Activity activity)
{
super();
mActivity = activity;
}
I'm new to Android studio.
I follow tutorials on Youtube and Google errors, but this time I cant seem to find how to fix this problem.
I'm creating a simple login-in and register app, that uses a mysql database. When I launch the app and click on the register button the app closes and states: "App stopped working".
I checked out the logcat and found this:
09-13 17:23:19.607 2229-2236/com.example.appname.appname E/art﹕ Failed sending reply to debugger: Broken pipe
09-13 17:23:47.756 2229-2229/com.example.appname.appname E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.appname.appname, PID: 2229
java.lang.IllegalStateException: Could not find method userReg(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.widget.Button
at android.view.View$DeclaredOnClickListener.resolveMethod(View.java:4479)
at android.view.View$DeclaredOnClickListener.onClick(View.java:4443)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Mainactivity.java
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void userReg()
{
startActivity(new Intent(this, Register.class));
}
public void userLogin(View view)
{
}
}
Register.java
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class Register extends Activity {
EditText ET_NAME,ET_USER_NAME,ET_USER_PASS;
String name,user_name,user_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_layout);
ET_NAME = (EditText) findViewById(R.id.name);
ET_USER_NAME = (EditText) findViewById(R.id.new_user_name);
ET_USER_PASS = (EditText) findViewById(R.id.new_user_pass);
}
public void userReg(View view)
{
name = ET_NAME.getText().toString();
user_name = ET_USER_NAME.getText().toString();
user_pass = ET_USER_PASS.getText().toString();
String method = "register";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method,name,user_name,user_pass);
finish();
}
}
Backgroundtask.java
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundTask extends AsyncTask<String, Void, String> {
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx=ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://10.0.2.2.2/webapp/register.php";
String login_url = "http://10.0.2.2.2/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 onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();
}
}
Change in your Mainactivity.java
public void userReg()
{
startActivity(new Intent(this, Register.class));
}
to
public void userReg(View v)
{
startActivity(new Intent(Mainactivity.this, Register.class));
}
And in Register.java
public void userReg(View view)
{
name = ET_NAME.getText().toString();
user_name = ET_USER_NAME.getText().toString();
user_pass = ET_USER_PASS.getText().toString();
String method = "register";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method,name,user_name,user_pass);
finish();
}
to
public void userReg(View view)
{
name = ET_NAME.getText().toString();
user_name = ET_USER_NAME.getText().toString();
user_pass = ET_USER_PASS.getText().toString();
String method = "register";
BackgroundTask backgroundTask = new BackgroundTask(Register.this);
backgroundTask.execute(method,name,user_name,user_pass);
finish();
}
The error appeared because the app couldn't find userReg(View) method that was written in the onClick attribute of your button in xml. You need to add parameter "View" in your method. Simply fix these lines of code:
MainActivity.java
public void userReg() {
startActivity(new Intent(this, Register.class));
}
to
public void userReg(View v) {
startActivity(new Intent(MainActivity.this, Register.class));
}