Android Studio, app stopped working - android

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));
}

Related

Android studio problems login validation

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.

AsyncTask seems not to proceed to onPre/PostExecute()

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

Progress Dialog in AsyncTask generating error on Activity Reference. Not an enclosing class

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;
}

Graph Facebook won't retrieve data

I'm trying to retrieve data from Facebook using graph Facebook, like Profile Pic, Gender, Age, Name, ID & Link, I'm getting Facebook Profile Pic only successfully but other won't retrieved. Please help!
MainActivity.java
package com.example.facebookprofile;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.facebookprofile.pictureAsync.onImageDownloaded;
import com.example.facebookprofile.profileAsync.profileImplement;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements profileImplement, onImageDownloaded {
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClick(View view){
EditText enterUsername = (EditText) findViewById(R.id.enterUsername);
String s = "https://graph.facebook.com/" + enterUsername.getEditableText().toString();
pictureAsync picTask = new pictureAsync(this);
profileAsync task = new profileAsync(this);
picTask.execute(s + "/picture?type=large");
picTask.delegate = this;
task.delegate = this;
task.execute(s);
}
public static User parseJSON(String jsonString) throws JSONException{
JSONObject top = new JSONObject(jsonString);
String name = "NA";
if(top.has("name"))
name = top.getString("name");
String username = top.getString("username");
String id = "NA";
if(top.has("id"))
id = top.getString("id");
String gender = "NA";
if(top.has("gender"))
gender = top.getString("gender");
String link = "https://www.facebook.com/"+username;
if(top.has("link"))
link = top.getString("link");
User output = new User(name, username, id, gender, link);
return output;
}
#Override
public void update(User user) {
// TODO Auto-generated method stub
if(user == null){
Toast t = Toast.makeText(this, "Invalid username", Toast.LENGTH_SHORT);
t.show();
}
else{
TextView name = (TextView) findViewById(R.id.name);
TextView id = (TextView) findViewById(R.id.id);
TextView gender = (TextView) findViewById(R.id.gender);
TextView link = (TextView) findViewById(R.id.link);
name.setText(user.name);
id.setText(user.id);
gender.setText(user.gender);
link.setText(user.link);
}
}
#Override
public void setImage(Bitmap bitmap) {
// TODO Auto-generated method stub
if(bitmap != null){
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(bitmap);
}
}
}
pictureAsync.java
package com.example.facebookprofile;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
public class pictureAsync extends AsyncTask<String, Integer, Bitmap> {
Context context;
onImageDownloaded delegate;
public interface onImageDownloaded{
public void setImage(Bitmap bitmap);
}
public pictureAsync(Context context) {
this.context = context;
}
#Override
protected Bitmap doInBackground(String... params) {
String picUrl = params[0];
try {
URL url = new URL(picUrl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if(delegate!=null)
delegate.setImage(result);
}
}
profileAsync.java
package com.example.facebookprofile;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONException;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
public class profileAsync extends AsyncTask<String, Integer, User> {
profileImplement delegate;
Context context;
ProgressDialog dialog;
public profileAsync(Context context) {
this.context = context;
}
#Override
public void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setMessage("Loading...Please wait");
dialog.show();
}
public interface profileImplement{
public void update(User user);
}
#Override
protected User doInBackground(String... arg) {
String user = arg[0];
try {
URL url = new URL(user);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream input = connection.getInputStream();
if(input == null) return null;
Scanner networkScanner = new Scanner(input);
StringBuffer buffer = new StringBuffer();
int count = 0;
while(networkScanner.hasNext()){
String line = networkScanner.next();
count += line.length();
//publishProgress(count);
buffer.append(line);
}
networkScanner.close();
return MainActivity.parseJSON(buffer.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(User result) {
dialog.dismiss();
if(delegate != null)
delegate.update(result);
}
// protected void onProgressUpdate(Integer... values) {
// // TODO Auto-generated method stub
// super.onProgressUpdate(values);
// dialog.setMessage("downloaded: " + values[0]);
// }
}
User.java
package com.example.facebookprofile;
public class User {
String name;
String username;
String id;
String gender;
String link;
User(String name, String username , String id , String gender , String link){
this.name = name;
this.username = username;
this.id = id;
this.gender = gender;
this.link = link;
}
}
It is a feature gone deprecated.

Intent in android error

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.

Categories

Resources