Why Toast in this application does not show anything? - java

I wrote an application that connect to wamp server ( with a MySQl datatbase that one of its rows in table users have Username="pooriya" and Password="123")
This application checks if Username "pooriya" exist then Toast the password and if does not exist Toast "no user"
When i run this app on emulator , it should Toast "123", but
empty Toast is shown . Why ?
Even when i change the User to a not existing Username , like "poori" , again empty Toast is shown . Why ?
database name is "note_test_2_db"
And when i enter the address "http://127.0.0.1:8080/mysite1/index.php" in my browser , it shows "no user" , then i guess that the php file works correctly and the problem is in my android code .
Thanks
package com.example.GetDataFromServer;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MyActivity extends Activity {
public static String res = "";
Button btn;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button);
new getdata("http://127.0.0.1:8080/mysite1/index.php", "pooriya").execute();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
}
});
}
}
package com.example.GetDataFromServer;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
/**
* Created with IntelliJ IDEA.
* User: Farid
* Date: 3/15/19
* Time: 4:09 PM
* To change this template use File | Settings | File Templates.
*/
public class getdata extends AsyncTask {
private String Link = "";
private String User = "";
public getdata(String link, String user) {
Link = link;
User = user;
}
#Override
protected String doInBackground(Object... objects) {
try {
String data = URLEncoder.encode("username", "UTF8") + "=" + URLEncoder.encode(User, "UTF8");
URL mylink = new URL(Link);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr= new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
MyActivity.res = sb.toString();
} catch (Exception e) {
}
return ""; //To change body of implemented methods use File | Settings | File Templates.
}
}
$con=mysql_connect("localhost","root","");
mysql_select_db("note_test_2_db",$con);
$user=$_POST['username'];
$sqlQ="select * from users where Username='$user'";
$result= mysql_Query($sqlQ);
$row=mysql_fetch_array($result);
if($row[0]){
print $row[1];
}
else{
print "no user";
}
mysql_close($con);

Problem: It seems your code to show Toast is incorrect.
new getdata("http://127.0.0.1:8080/mysite1/index.php", "pooriya").execute();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
}
});
When the first line is executed, the app will start the AsyncTask which connects to your server to get the response ("123" or "No User").
If you click on the button btn before the AsyncTask completed, at this time, the value of res is "", that why you always get empty Toast.
Solution: You can do the following steps
Step 1: Because getdata is a separate class, so you need to define an interface to pass data ("123" or "No User" or any value) back to MyActivity.
public interface OnDataListener {
void onData(String result);
}
Step 2: Modify getdata class
public class getdata extends AsyncTask<Object, Void, String> {
private String Link = "";
private String User = "";
private WeakReference<OnDataListener> mListener;
public getdata(String link, String user, OnDataListener listener) {
Link = link;
User = user;
mListener = new WeakReference<>(listener);
}
#Override
protected String doInBackground(Object... objects) {
try {
String data = URLEncoder.encode("username", "UTF8") + "=" + URLEncoder.encode(User, "UTF8");
URL mylink = new URL(Link);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
// This string will pass as param of onPostExecute method.
return sb.toString(); // Will return "123" or "No User" if there is no exception occurs.
} catch (Exception e) {
}
// If your app reach this line, it means there is an exception occurs, using a unique string for debugging.
// This string will pass as param of onPostExecute method
return "An exception has been caught!!!";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Pass the result back to MyActivity's onData method.
if (mListener != null && mListener.get() != null) {
mListener.get().onData(result);
}
}
}
Step 3: Let MyActivity implements OnDataListener interface.
public class MyActivity extends AppCompatActivity implements OnDataListener {
public static String res = "";
Button btn;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button);
new getdata("http://127.0.0.1:8080/mysite1/index.php", "pooriya", this).execute();
// TODO: Comment-out this code
// btn.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
// }
// });
}
#Override
public void onData(String result) {
// result is passed from the AsyncTask's onPostExecute method.
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
Note: Because you do not use any loading indicator while connecting to the server, so you need to wait a few seconds to see the Toast on the screen.

I solved the problem . I should use http://10.0.2.2:8080/mysite1/index.php instead http://127.0.0.1:8080/mysite1/index.php

Related

Android app making JSON call gets unexpected data from server, but same call works in browser

I have an Android app that makes a server call which returns JSON.
The server code returns the right string if I enter the URL into a browser. But it creates exceptions in the Java app (different issues with http and https server calls).
https://www.problemio.com/auth/mobile_login.php?login=test.name#gmail.com&password=130989
Returns this string:
[{"user_id":"1601470","email":"test.name#gmail.com","first_name":"TestName","last_name":null}]
And this is the Java call that parses the JSON but gives an Exception:
#Override
protected void onPostExecute(String result)
{
try {
dialog.dismiss();
} catch (Exception ee) {
// nothing
}
if ( connectionError == true )
{
Toast.makeText(getApplicationContext(), "Please try again. Possible Internet connection error.", Toast.LENGTH_LONG).show();
}
if ( result != null && result.equals( "no_such_user") )
{
Toast.makeText(getApplicationContext(), "Your email and password do not match out records. Please try again or create and account.", Toast.LENGTH_LONG).show();
//final TextView login_error = (TextView) findViewById(R.id.login_error);
}
else
{
Log.d( "CONNECTION*** ERRORS: " , "ok 3 and result length: " + result.length() );
String firstName = null;
String lastName = null;
String email = null;
String user_id = null;
try
{
JSONArray obj = new JSONArray(result);
JSONObject o = obj.getJSONObject(0);
firstName = o.getString("first_name");
lastName = o.getString("last_name");
email = o.getString("email");
user_id = o.getString("user_id");
}
catch ( Exception e )
{
Log.d( "JSON ERRORS: " , "something happened ****" + e.getMessage() );
}
// 1) First, write to whatever local session file that the person is logged in
// - I just really need user id and name and email. And store that.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(
LoginActivity.this);
if ( user_id != null && user_id.trim().length() > 0 && !user_id.trim().equals("null") )
{
prefs.edit()
.putString("first_name", firstName)
.putString("last_name", lastName)
.putString("email", email)
.putString("user_id", user_id)
.putBoolean("working", true)
.commit();
if ( user_id.equals("1"))
{
prefs.edit()
.putString("community_subscription", "1")
.commit();
}
}
}
}
}
And this is the exception message:
End of input at character 0 of
It just looks like the string is 0 characters long.
Any idea why this is happening? Before I switched my site to https this call used to work without problems.
Also the server makes an http call. If I change it to https it returns a whole bunch of HTML which is weird since I don't actually send that back.
This is my doInBackground method:
#Override
protected String doInBackground(String... theParams)
{
String myUrl = theParams[0];
final String myEmail = theParams[1];
final String myPassword = theParams[2];
String charset = "UTF-8";
Authenticator.setDefault(new Authenticator()
{
#Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication( myEmail, myPassword.toCharArray());
}
});
Edit
If my doInBackground method is inside the
public class DownloadWebPageTask extends AsyncTask<String, Void, String>
Can it be that the server is just too slow to return the string and that is why it is getting null?
It is always crashing on this with the result string being empty:
JSONArray obj = new JSONArray(result);
Edit 2
Here is the full code:
package com.problemio;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import org.json.JSONArray;
import org.json.JSONObject;
import com.flurry.android.FlurryAgent;
import utils.SendEmail;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginActivity extends BaseActivity
{
//private TextView textView;
private Dialog dialog;
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
FlurryAgent.onStartSession(this, "8CA5LTZ5M73EG8R35SXG");
setContentView(R.layout.login);
//final TextView emailask = (TextView) findViewById(R.id.email_ask);
// Show form for login_email
final EditText loginEmail = (EditText) findViewById(R.id.login_email);
//String name = loginEmail.getText().toString();
// Show field for password
final EditText password = (EditText) findViewById(R.id.password);
//String text = password.getText().toString();
//Log.d( "First parameters: " , "Login email: " + loginEmail + " AND login password: " + text);
// Show button for submit
Button submit = (Button)findViewById(R.id.submit);
submit.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
String email = loginEmail.getText().toString();
String pass = password.getText().toString();
//Set the email pattern string
// Pattern pattern = Pattern.compile(".+#.+\\.[a-z]+");
// //Match the given string with the pattern
// Matcher m = pattern.matcher(email);
// //check whether match is found
// boolean matchFound = m.matches();
// TODO: VALIDATE!!!
if ( email == null || email.trim().length() < 2 )
{
Toast.makeText(getApplicationContext(), "Please enter a valid email address.", Toast.LENGTH_LONG).show();
}
else
if ( pass == null || pass.trim().length() < 2 )
{
Toast.makeText(getApplicationContext(), "Please enter a correct password.", Toast.LENGTH_LONG).show();
}
else
{
sendFeedback(pass, email);
}
}
});
// Show button for submit
Button forgot_password = (Button)findViewById(R.id.forgot_password);
forgot_password.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Please wait...", Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this, ForgotPasswordActivity.class);
LoginActivity.this.startActivity(intent);
}
});
// Now add messaging for creating a profile
final TextView create_profile_message = (TextView) findViewById(R.id.create_profile_message);
Button create_profile = (Button)findViewById(R.id.create_profile);
create_profile.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
//sendEmail("Create Profile Clicked", "From Login screen, someone clicked on the create profile button" );
Intent myIntent = new Intent(LoginActivity.this, CreateProfileActivity.class);
LoginActivity.this.startActivity(myIntent);
}
});
}
public void sendFeedback(String pass , String email)
{
String[] params = new String[] { "http://www.problemio.com/auth/mobile_login.php", email, pass };
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(params);
}
// Subject , body
public void sendEmail( String subject , String body )
{
String[] params = new String[] { "http://www.problemio.com/problems/send_email_mobile.php", subject, body };
SendEmail task = new SendEmail();
task.execute(params);
}
public class DownloadWebPageTask extends AsyncTask<String, Void, String>
{
private boolean connectionError = false;
#Override
protected void onPreExecute( )
{
dialog = new Dialog(LoginActivity.this);
dialog.setContentView(R.layout.please_wait);
dialog.setTitle("Logging You In");
TextView text = (TextView) dialog.findViewById(R.id.please_wait_text);
text.setText("Please wait while you are being logged in...");
dialog.show();
}
// orig
#Override
protected String doInBackground(String... theParams)
{
String myUrl = theParams[0];
final String myEmail = theParams[1];
final String myPassword = theParams[2];
String charset = "UTF-8";
Authenticator.setDefault(new Authenticator()
{
#Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication( myEmail, myPassword.toCharArray());
}
});
String response = null;
String stringUrl = "https://www.problemio.com/auth/mobile_login.php?login=test.name#gmail.com&password=130989";
String result = "";
String inputLine;
try
{
String query = String.format("login=%s&password=%s",
URLEncoder.encode(myEmail, charset),
URLEncoder.encode(myPassword, charset));
final URL url = new URL( myUrl + "?" + query );
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("login", myEmail);
conn.setRequestProperty("password", myPassword);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.connect();
final InputStream is = conn.getInputStream();
final byte[] buffer = new byte[8196];
int readCount;
final StringBuilder builder = new StringBuilder();
while ((readCount = is.read(buffer)) > -1)
{
builder.append(new String(buffer, 0, readCount));
}
response = builder.toString();
}
catch (Exception e)
{
sendEmail ( "Login Activity 1 Network Error" , "Error: " + e.getMessage() );
}
return response;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
try {
dialog.dismiss();
} catch (Exception ee) {
// nothing
}
if ( connectionError == true )
{
Toast.makeText(getApplicationContext(), "Please try again. Possible Internet connection error.", Toast.LENGTH_LONG).show();
}
if ( result != null && result.equals( "no_such_user") )
{
Toast.makeText(getApplicationContext(), "Your email and password do not match out records. Please try again or create and account.", Toast.LENGTH_LONG).show();
//final TextView login_error = (TextView) findViewById(R.id.login_error);
}
else
{
String firstName = null;
String lastName = null;
String email = null;
String user_id = null;
try
{
JSONArray obj = new JSONArray(result);
Log.d( "CONNECTION*** ERRORS: " , ".....5" );
JSONObject o = obj.getJSONObject(0);
firstName = o.getString("first_name");
lastName = o.getString("last_name");
email = o.getString("email");
user_id = o.getString("user_id");
}
catch ( Exception e )
{
Log.d( "JSON ERRORS: " , "some crap happened ****" + e.getMessage() );
}
// 1) First, write to whatever local session file that the person is logged in
// - I just really need user id and name and email. And store that.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(
LoginActivity.this);
if ( user_id != null && user_id.trim().length() > 0 && !user_id.trim().equals("null") )
{
prefs.edit()
.putString("first_name", firstName)
.putString("last_name", lastName)
.putString("email", email)
.putString("user_id", user_id)
.putBoolean("working", true)
.commit();
if ( user_id.equals("1"))
{
prefs.edit()
.putString("community_subscription", "1")
.commit();
}
}
}
}
}
// TODO: see if I can get rid of this
public void readWebpage(View view)
{
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.problemio.com/auth/mobile_login.php" });
}
#Override
public void onStop()
{
super.onStop();
}
}
ISSUE #1
From your question description:
The server code returns the right string if I enter the URL into a
browser.
I'm assuming you are using HTTP GET. However you are using HTTP POST in your code instead:
String query = String.format("login=%s&password=%s",
URLEncoder.encode(myEmail, charset),
URLEncoder.encode(myPassword, charset));
final URL url = new URL( myUrl + "?" + query );
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST"); // <----------- replace with "GET"
ISSUE #2
conn.setDoOutput(true);
When set to true the request method is changed to POST, since GET or DELETE can't have a request body. To continue with a GET request you must set conn.setDoOutput(false);
Also, comment out those lines:
//conn.setRequestProperty("login", myEmail);
//conn.setRequestProperty("password", myPassword);
//conn.setDoOutput(true);
ISSUE #3
task.execute(new String[] { "http://www.problemio.com/auth/mobile_login.php" });
From Android 8: Cleartext HTTP traffic not permitted
You must change the URL from http to https or add android:usesCleartextTraffic="true" in the manifest. This will only effect on devices running API level 23+. Before 23+ http is allowed by default.
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>
</manifest>
For me using https worked properly.
ISSUE #4
Upon providing wrong credentials your server is sending a plain text message
no_such_user
Which needs to be replaced with a valid JSON string.
From my end, the code you provided is working properly after fixing those issues.
I tried your code using HttpURLConnection in async task, It gave me the desired output without error.. But if I give different password in the get url.. the response is not JSONObject. It is coming as String value. may be that causing the issue(u handle that also in postexecute method)
public class HttpGetRequest extends AsyncTask<String, Void, String> {
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
#Override
protected String doInBackground(String... params) {
String stringUrl = "https://www.problemio.com/auth/mobile_login.php?login=test.name#gmail.com&password=130989";
String result = "";
String inputLine;
try {
//Create a URL object holding our url
URL myUrl = new URL(stringUrl);
//Create a connection
HttpURLConnection connection = (HttpURLConnection)
myUrl.openConnection();
//Set methods and timeouts
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
//Connect to our url
connection.connect();
//Create a new InputStreamReader
InputStreamReader streamReader = new
InputStreamReader(connection.getInputStream());
//Create a new buffered reader and String Builder
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
//Check if the line we are reading is not null
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
//Close our InputStream and Buffered reader
reader.close();
streamReader.close();
//Set our result equal to our stringBuilder
result = stringBuilder.toString();
} catch (Exception e) {
}
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// textView.setText("Response is: " + response);
try {
JSONArray obj = new JSONArray(result);
JSONObject o = obj.getJSONObject(0);
String firstName = o.getString("first_name");
String lastName = o.getString("last_name");
String email = o.getString("email");
String user_id = o.getString("user_id");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Looking your Json I can see a null
[
{
"user_id": "1601470",
"email": "test.name#gmail.com",
"first_name": "TestName",
"last_name": null
}
]
Json files accept nulls, but json objects do not accept it.
The application is crashing when you try to get the last_name.
Instead of null use empty.
[
{
"user_id": "1601470",
"email": "test.name#gmail.com",
"first_name": "TestName",
"last_name": ""
}
]
Regards
As per google this is old technique Retrieve API data using AsyncTask, I prefer Retrofit + RxJava + RxAndroid + GSON.
It will remove all your boilerplate code. It is so easy to use Retrofit.
Add Below dependency in your app,
//retrofit
implementation 'com.squareup.retrofit2:retrofit:2.6.1'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'
//Rx android
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.2.8'
Create MyRetrofit class,
import com.google.gson.GsonBuilder;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MyRetrofit {
private static Retrofit retrofit = null;
public static Retrofit getInstance() {
String BASE_URL = "https://www.problemio.com/";
if (retrofit == null) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.readTimeout(60, TimeUnit.MINUTES);
httpClient.connectTimeout(60, TimeUnit.SECONDS);
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(logging);
}
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(httpClient.build())
.build();
}
return retrofit;
}
}
Create APIService Class,
import in.kintanpatel.customrecylerview.model.LoginBean;
import io.reactivex.Observable;
import retrofit2.Response;
import retrofit2.http.GET;
import retrofit2.http.Query;
/**
* Created by kintan on 8/11/18.
*/
public interface APIService {
//Add All your method here
#GET("auth/mobile_login.php/")
Observable<Response<ArrayList<LoginBean>>> doLogin(#Query("login") String login, #Query("password") String password);
}
That's it now call your API stuff here,
private void doLoginAPI(String userName, String password) {
//Show Loading here
MyRetrofit.getInstance().create(APIService.class).doLogin(userName, password)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Response<ArrayList<LoginBean>>>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(Response<ArrayList<LoginBean>> response) {
//Hide Loading here
if (response.isSuccessful()) { //check HTTP Response
LoginBean bean = response.body().get(0);
Log.e("USER_INFO", "User ID: " + bean.getUserId());
Log.e("USER_INFO", "User First Name : " + bean.getFirstName());
Log.e("USER_INFO", "User Last Name : " + bean.getLastName());
Log.e("USER_INFO", "User Email : " + bean.getEmail());
}
}
#Override
public void onError(Throwable e) {
Log.e("USER_INFO", e.getMessage());
}
#Override
public void onComplete() {
}
});
}
And just call your method where you want:
doLoginAPI("test.name#gmail.com", "130989");
And Your output like,
11-08 14:44:59.946 25447-25447/com.kintanpatel.baserecyclerview E/USER_INFO: User ID: 1601470
11-08 14:44:59.946 25447-25447/com.kintanpatel.baserecyclerview E/USER_INFO: User First Name : TestName
11-08 14:44:59.946 25447-25447/com.kintanpatel.baserecyclerview E/USER_INFO: User Last Name : null
11-08 14:44:59.946 25447-25447/com.kintanpatel.baserecyclerview E/USER_INFO: User Email : test.name#gmail.com

Where should I put my AsyncTask class for my app?

So I have been trying to make a feature in my app where I can login and then fetch data from my database through the Django REST Framework. My logging in works as it only uses POST, but retrieving items does not work.
For some reason my AsyncTask does not get called for retrieving posts.
I have placed my AsyncTask for both activities, which are login and posts, on a separate java file only for handling Web Server stuff.
I am wondering if this is because I should put AsyncTask on each activities.
login.java
public class Login extends AppCompatActivity {
Button LoginButton;
EditText uUserName, uPassWord;
WSAdapter.SendAPIRequests AuthHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//SetupHomeBtn = (ImageButton) findViewById(R.id.SetupHomeBtn);
LoginButton = (Button) findViewById(R.id.LoginButton);
uUserName = (EditText) findViewById(R.id.LoginUserBox);
uPassWord = (EditText) findViewById(R.id.LoginPassBox);
//AuthHelper = new WSAdapter().new SendDeviceDetails();
// Moves user to the main page after validation
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// gets the username and password from the EditText
String strUserName = uUserName.getText().toString();
String strPassWord = uPassWord.getText().toString();
// API url duh
String APIUrl = "http://192.168.0.18:8000/token-auth/";
// If the user is authenticated, then transfer to the MainActivity page
if (APIAuthentication(strUserName, strPassWord, APIUrl)){
startActivity(new Intent(Login.this, Posts.class));
}
}
});
}
private boolean APIAuthentication(String un, String pw, String url){
// when it wasn't static -> AuthHelper = new WSAdapter().new SendAPIRequests();
AuthHelper = new WSAdapter.SendAPIRequests();
JSONObject postData = new JSONObject();
try {
// Attempt to input info to the Django API
postData.put("username", un);
postData.put("password", pw);
// Putting the data to be posted in the Django API
AuthHelper.execute(url, postData.toString());
return true;
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
posts.java
public class Posts extends AppCompatActivity {
TextView postsSect;
Button postsDoneBtn;
WSAdapter.SendAPIRequests PostsHelper;
StringBuilder postsBuffer = new StringBuilder();
#Override
protected void onResume(){
super.onResume();
PostsDetails postDetailsHelper = new PostsDetails();
postDetailsHelper.ListPosts();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
PostsDetails postDetailsHelper = new PostsDetails();
postsDoneBtn = (Button) findViewById(R.id.PostsDoneButton);
postDetailsHelper.callPostDetails("192.168.0.18:8000/api");
postDetailsHelper.ListPosts();
postDetailsHelper.postDetailsCalled('n');
postsDoneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Posts.this, MainActivity.class));
}
});
}
public class PostsDetails {
//String post_title, post_content;
ArrayList<Integer> post_id = new ArrayList<Integer>();
ArrayList<String> post_title = new ArrayList<String>();
ArrayList<String> post_content = new ArrayList<String>();
boolean isPDCalled;
// sets if Post details are called
boolean postDetailsCalled(char called) {
if (called == 'y'){
return true;
}
return false;
}
// checks if postsDetails functions are called for AsyncTask
boolean getIsPDCalled(){
return isPDCalled;
}
// calls the execute for AsyncTask
private void callPostDetails(String theurl){
PostsHelper = new WSAdapter.SendAPIRequests();
// sets if post details are called
postDetailsCalled('y');
// executes AsyncTask
PostsHelper.execute(theurl);
}
// sets values for the posts arrays
public void setPost(int p_id, String p_title, String p_content) {
post_id.add(p_id);
post_title.add(p_title);
post_content.add(p_content);
}
// Lists the posts from the database
public void ListPosts() {
/////////// add functionality if a post was deleted and was clicked
postsSect = (TextView) findViewById(R.id.PostsSection);
postsSect.setText(post_title.get(post_title.size()) + "\n");
for (int i = post_id.size() - 1; i > 0; i--)
{
postsSect.append(post_title.get(i));
}
}
}
}
WSAdapter.java
// I forgot what WS stands for, but this class serves as an adapter for JSON and Online stuff
// I think it stands for With-Server Adapter
public class WSAdapter extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
static public class SendAPIRequests extends AsyncTask<String, String, String> {
// Add a pre-execute thing
#Override
protected String doInBackground(String... params) {
Log.e("TAG", params[0]);
Log.e("TAG", params[1]);
String data = "";
HttpURLConnection httpURLConnection = null;
try {
// Sets up connection to the URL (params[0] from .execute in "login")
httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
// Sets the request method for the URL
httpURLConnection.setRequestMethod("POST");
// Tells the URL that I am sending a POST request body
httpURLConnection.setDoOutput(true);
// To write primitive Java data types to an output stream in a portable way
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
// Writes out a byte to the underlying output stream of the data posted from .execute function
wr.writeBytes("postData=" + params[1]);
// Flushes the postData to the output stream
wr.flush();
wr.close();
// Representing the input stream
InputStream in = httpURLConnection.getInputStream();
// Preparing input stream bytes to be decoded to charset
InputStreamReader inputStreamReader = new InputStreamReader(in);
StringBuilder dataBuffer = new StringBuilder();
// Translates input stream bytes to charset
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
// concatenates data characters from input stream
dataBuffer.append(current);
}
data = dataBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Disconnects socket after using
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
Log.e("TAG", data);
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
Posts.PostsDetails postsHelper = new Posts().new PostsDetails();
// For posts
try {
if (postsHelper.getIsPDCalled()){
JSONObject pJObj = new JSONObject(result);
JSONArray pJObjArray = pJObj.getJSONArray("posts");
for (int i = 0; i < pJObjArray.length(); i++) {
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
postsHelper.setPost(pJObj_data.getInt("id"), "post_title", "post_content");
}
}
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
}
}
}
Yes, you can and should put the network calls functions in a separate java file for better readability and test-coverage.
Apart from that, i would suggest to use Retrofit as your HTTP client. It helps you to manage all the dirty things like headers and converters etc, so you can put all your effort on your logic and implementing your callback actions.

Creating a android app that sends POST request to PHP [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I've already tried several options to send a post request from an android app to a server running a PHP file
I need to send a POST Request where the following parameters: id = 0 & balance = 666
I have the following code on my app and wen the app goes to send the request the app crashes
Can some one help?
ANDROID CODE:
package com.example.hk300.jsonpost;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import static android.R.id.message;
public class MainActivity extends AppCompatActivity {
// Remove the below line after defining your own ad unit ID.
private static final String TOAST_TEXT = "Test ads are being shown. "
+ "To show live ads, replace the ad unit ID in res/values/strings.xml with your own ad unit ID.";
private static final int START_LEVEL = 1;
private int mLevel;
private Button mNextLevelButton;
private InterstitialAd mInterstitialAd;
private TextView mLevelTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the next level button, which tries to show an interstitial when clicked.
mNextLevelButton = ((Button) findViewById(R.id.next_level_button));
mNextLevelButton.setEnabled(false);
mNextLevelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showInterstitial();
}
});
// Create the text view to show the level number.
mLevelTextView = (TextView) findViewById(R.id.level);
mLevel = START_LEVEL;
// Create the InterstitialAd and set the adUnitId (defined in values/strings.xml).
mInterstitialAd = newInterstitialAd();
loadInterstitial();
// Toasts the test ad message on the screen. Remove this after defining your own ad unit ID.
Toast.makeText(this, TOAST_TEXT, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private InterstitialAd newInterstitialAd() {
InterstitialAd interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
mNextLevelButton.setEnabled(true);
}
#Override
public void onAdFailedToLoad(int errorCode) {
mNextLevelButton.setEnabled(true);
}
#Override
public void onAdClosed() {
// Proceed to the next level.
goToNextLevel();
}
});
return interstitialAd;
}
private void showInterstitial() {
// Show the ad if it's ready. Otherwise toast and reload the ad.
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show();
goToNextLevel();
}
}
private void loadInterstitial() {
// Disable the next level button and load the ad.
mNextLevelButton.setEnabled(false);
AdRequest adRequest = new AdRequest.Builder()
.setRequestAgent("android_studio:ad_template").build();
mInterstitialAd.loadAd(adRequest);
}
private void goToNextLevel() {
// Show the next level and reload the ad to prepare for the level after.
mLevelTextView.setText("Level " + (++mLevel));
mInterstitialAd = newInterstitialAd();
loadInterstitial();
new BackgroundTask().execute();
}
public class BackgroundTask extends AsyncTask<Void,Void,String> {
#Override
protected void onPreExecute(){
//Do UI operation here and onPostExecute
//TextView textview = (TextView)findViewById(R.id.credits);
//textview.setText(message);
}
#Override
protected String doInBackground(Void... params) {
OutputStream os = null;
InputStream is = null;
HttpURLConnection conn = null;
String contentAsString = null;
try {
URL url = new URL("https://disjunct-swabs.000webhostapp.com/testapp.php");
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", "0");
jsonObject.put("balance", "666");
String message = jsonObject.toString();
//You cannot perform these UI operation on non-UI thread
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /*milliseconds*/);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(message.getBytes().length);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(message);
Log.e("JSON Input", message);
wr.flush();
wr.close();
conn.connect();
is = conn.getInputStream();
contentAsString = is.toString();
} catch (IOException e) {
Log.d("shit", "Shit");
} catch (JSONException e) {
Log.d("shit", "Shit");
} finally {
conn.disconnect();
}
//return response to onPostExecute()
return contentAsString;
}
#Override
protected void onPostExecute(String res){
//Do anything with response
}
}
}
Are you sure you are not running this in the main UI thread. Create a new thread or use AsyncTask to perform network operations.
public class BackgroundTask extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try {
URL url = new URL("https://disjunct-swabs.000webhostapp.com/testapp.php");
JSONObject postDataParams = new JSONObject();
postDataParams.put("id", "0");
postDataParams.put("balance", "666");
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
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();
}
}
In the above thread, you cannot declare, initialize or perform operation(setText) on any view, because they must happen on UI thread only. Put that in onPreExecute or onPostExecute methods
Now you cun run the code by
new BackgroundTask().execute();
Also add permission in manifest
<uses-permission android:name="android.permission.INTERNET" />
If you are using Android M or above, you must ask permission during runtime as well. This should be your goToNextLevel() method
private void goToNextLevel() {
// Show the next level and reload the ad to prepare for the level after.
mLevelTextView.setText("Level " + (++mLevel));
mInterstitialAd = newInterstitialAd();
loadInterstitial();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.INTERNET
}, 10);
}
}
new BackgroundTask().execute();
}

Using GCM to send push notification from one activity to another - Android Studio

I am currently programming an android application in Android Studio. I am trying to implement a push notification service with GCM. The push notification will be sent from one user account to another user account, the second user will accept and then the two accounts will be linked. I have the two accounts set up on a mySQL server using 000webhost.com. I tried to followed this tutorial , link, to implement GCM but I can't figure out how I send and receive the notification.
This is where I get the registration ID:
package com.jack.pointcollector;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import java.io.IOException;
public class GCMClientManager {
// Constants
public static final String TAG = "GCMClientManager";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
// Member variables
private GoogleCloudMessaging gcm;
private String regID;
private String projectNumber;
private Activity activity;
public GCMClientManager(Activity activity, String projectNumber) {
this.activity = activity;
this.projectNumber = projectNumber;
this.gcm = GoogleCloudMessaging.getInstance(activity);
}
/**
* #return Application's version code from the {#code PackageManager}.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
// Register if needed or fetch from local store
public void registerIfNeeded(final RegistrationCompletedHandler handler) {
if (checkPlayServices()) {
regID = getRegistrationId(getContext());
if (regID.isEmpty()) {
registerInBackground(handler);
} else { // got id from cache
Log.i(TAG, regID);
handler.onSuccess(regID, false);
}
} else { // no play services
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
/**
* Registers the application with GCM servers asynchronously.
* <p>
* Stores the registration ID and app versionCode in the application's
* shared preferences.
*/
private void registerInBackground(final RegistrationCompletedHandler handler) {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getContext());
}
InstanceID instanceID = InstanceID.getInstance(getContext());
regID = instanceID.getToken(projectNumber, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Log.i(TAG, regID);
// Persist the regID - no need to register again.
storeRegistrationId(getContext(), regID);
} catch (IOException ex) {
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
handler.onFailure("Error :" + ex.getMessage());
}
return regID;
}
#Override
protected void onPostExecute(String regId) {
if (regId != null) {
handler.onSuccess(regId, true);
}
}
}.execute(null, null, null);
}
/**
* Gets the current registration ID for application on GCM service.
* <p>
* If result is empty, the app needs to register.
*
* #return registration ID, or empty string if there is no existing
* registration ID.
*/
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
/**
* Stores the registration ID and app versionCode in the application's
* {#code SharedPreferences}.
*
* #param context application's context.
* #param regId registration ID
*/
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.apply();
}
private SharedPreferences getGCMPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
// how you store the regID in your app is up to you.
return getContext().getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
}
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
}
return false;
}
return true;
}
private Context getContext() {
return activity;
}
private Activity getActivity() {
return activity;
}
public static abstract class RegistrationCompletedHandler {
public abstract void onSuccess(String registrationId, boolean isNewRegistration);
public void onFailure(String ex) {
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
Log.e(TAG, ex);
}
}
}
This is my GCMListnerService class:
package com.jack.pointcollector;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import com.google.android.gms.gcm.GcmListenerService;
public class PushNotificationManager extends GcmListenerService{
#Override
public void onMessageReceived(String from, Bundle data) {
childNotification(from);
super.onMessageReceived(from, data);
}
private AlertDialog childNotification(String name) {
AlertDialog.Builder response = new AlertDialog.Builder(this.getBaseContext());
response.setMessage(name + " has added you as their child. Is this correct?");
response.setTitle("Point Collector");
response.setPositiveButton("Correct", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
response.setNegativeButton("I don't know them", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
response.setCancelable(false);
return response.create();
}
}
and finally the class the I want to send the notification from
package com.jack.pointcollector;
import android.app.Activity;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class Add_Child extends Activity implements View.OnClickListener {
Button bAddChild;
EditText etUsername, etEmail;
String PROJECT_NUMBER = "76770391940";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add__child);
bAddChild = (Button) findViewById(R.id.addButton);
etUsername = (EditText) findViewById(R.id.name);
etEmail = (EditText) findViewById(R.id.child_email);
bAddChild.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.addButton:
GCMClientManager pushClientManager = new GCMClientManager(this, PROJECT_NUMBER);
pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
#Override
public void onSuccess(String registrationId, boolean isNewRegistration) {
Log.d("Registration id", registrationId);
//send this registrationId to your server
toServer(registrationId);
}
#Override
public void onFailure(String ex) {
super.onFailure(ex);
}
});
break;
}
}
private void toServer(final String id) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("http://point_collector.netau.net/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder().appendQueryParameter("id", id);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
//Gets the response code to ensure this was succesful.
int code = conn.getResponseCode();
Log.d("code", Integer.toString(code));
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
}
}
I have looked and loads of video tutorials as well as online tutorials and can't figure it out at all. If anybody can help me out I would greatly appreciate it.
Thanks
edit - Still really stuck on this if anybody at all could offer some insight!

Google Cloud messaging service returning empty registration id

I'm running into an issue implementing Google Cloud Messaging. When i try to register my emulator i'm suppost to get the Registration ID of the device, which in this case is my emulator. So when i looked around i saw i needed to link a google account so i did that but i still have the same issue. it returns that it is a new registration but the registration id is empty. could someone help me in the right direction? If you need to know anything else let me know. Thanks in advance
Code:
LoginActivity.java
package com.vict.voffice;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.vict.voffice.utilities.Dialogs;
import com.vict.voffice.utilities.GCMClientManager;
import com.vict.voffice.utilities.UserDetailCache;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class LoginActivity extends Activity {
EditText mNaam;
EditText mVersie;
EditText mWachtwoord;
String PROJECT_NUMBER = "##########";
private GCMClientManager pushClientManager;
private Context cont = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
cont = this;
pushClientManager = new GCMClientManager(this, PROJECT_NUMBER);
mNaam = (EditText)findViewById(R.id.editText_login);
mVersie = (EditText)findViewById(R.id.editText_bedrijf);
mWachtwoord = (EditText)findViewById(R.id.editText_wachtwoord);
final Button button = (Button) findViewById(R.id.btnLogin);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
#Override
public void onSuccess(String registrationId, boolean isNewRegistration) {
//Dialogs.LoginDialog(cont).show();
Toast.makeText(getApplicationContext(), "Regid: "+registrationId+" "+isNewRegistration, Toast.LENGTH_SHORT).show();
//Login(mNaam.getText().toString(), mWachtwoord.getText().toString(), mVersie.getText().toString(), pushClientManager.getRegistrationId(cont));
}
#Override
public void onFailure(String ex) {}});
Log.d("DBG", "Login Pressed");
}
});
Log.d("DBG", ""+UserDetailCache.GetNodeFromFile(cont));
if(UserDetailCache.GetNodeFromFile(cont) != null || UserDetailCache.GetNodeFromFile(cont) != "" || UserDetailCache.GetNodeFromFile(cont) != "null" || UserDetailCache.GetNodeFromFile(cont).isEmpty()){
if(UserDetailCache.GetUserNameFromFile(cont) != null || UserDetailCache.GetUserNameFromFile(cont) != "" || UserDetailCache.GetUserNameFromFile(cont) != "null"){
if(UserDetailCache.GetPasswordFromFile(cont) != null || UserDetailCache.GetPasswordFromFile(cont) != "" || UserDetailCache.GetPasswordFromFile(cont) != "null"){
Log.d("DBG", "Filling Fields from DB");
mNaam.setText(UserDetailCache.GetUserNameFromFile(getApplicationContext()));
mWachtwoord.setText(UserDetailCache.GetPasswordFromFile(getApplicationContext()));
mVersie.setText(UserDetailCache.GetNodeFromFile(getApplicationContext()));
button.performClick();
}else{
Log.d("DBG", "No Password");
}
}else{
Log.d("DBG", "No Username");
}
}else{
Log.d("DBG", "No Node");
}
}
#Override
public void onBackPressed(){
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
super.onBackPressed();
System.exit(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void Login(String Username, String Password, String Node, String Token){
class LoginAsyncTask extends AsyncTask<String, Void, String>{
UserDetailCache Dtc = new UserDetailCache();
String uniqueKey = "";
#Override
protected void onPreExecute(){
super.onPreExecute();
//Dialogs.LoginDialog(getApplicationContext()).show();
}
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramPassword = params[1];
String paramVersion = params[2];
uniqueKey = params[3];
Log.d("LoginActivity", "Token: " + uniqueKey);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://node11.voffice.nl/login/appcheck.asp?login=" + paramUsername + "&wachtw=" + paramPassword + "&versie=" + paramVersion + "&token=" + uniqueKey);
//Log.e("HTTP", "send link: " + httpPost.getURI());
try{
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
}catch (ClientProtocolException cpe){
// Log.e("HTTP", "First Exception, httpResponse : " + cpe);
cpe.printStackTrace();
}catch (IOException ioe){
// Log.e("HTTP", "Second Exception, httpResonse : " + ioe);
ioe.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
Log.e("HTTP", "Server Responded with : " + result);
String splitResult[] = result.split("\\|");
if(splitResult[0].equals("OK") && splitResult != null){
String tempCompany = splitResult[1].substring(8);
User usr = new User(splitResult[1], tempCompany, splitResult[2], uniqueKey, splitResult[4], splitResult[3]);
Dialogs.LoginDialog(getApplicationContext()).hide();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(intent, 0);
}else{
Dialogs.TextDialog(getApplicationContext(), "Verkeerde Logingegeven", Toast.LENGTH_LONG);
Dialogs.LoginDialog(getApplicationContext()).hide();
}
Dialogs.TextDialog(getApplicationContext(), "", Toast.LENGTH_LONG);
Dialogs.LoginDialog(getApplicationContext()).hide();
}
}
LoginAsyncTask Logintask = new LoginAsyncTask();
Logintask.execute(Username, Password, Node, Token);
}
}
GCMClientManager.java
package com.vict.voffice.utilities;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.io.IOException;
/**
* Created by Kevin on 3/3/2015.
*/
public class GCMClientManager {
// Constants
public static final String TAG = "GCMClientManager";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "6";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
// Member variables
private GoogleCloudMessaging gcm;
private String regid;
private String projectNumber;
private Activity activity;
public static abstract class RegistrationCompletedHandler {
public abstract void onSuccess(String registrationId, boolean isNewRegistration);
public void onFailure(String ex) {
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
Log.e(TAG, ex);
}
}
public GCMClientManager(Activity activity, String projectNumber) {
this.activity = activity;
this.projectNumber = projectNumber;
this.gcm = GoogleCloudMessaging.getInstance(activity);
}
// Register if needed or fetch from local store
public void registerIfNeeded(final RegistrationCompletedHandler handler) {
if (checkPlayServices()) {
regid = getRegistrationId(getContext());
if (regid.isEmpty()) {
registerInBackground(handler);
} else { // got id from cache
Log.i(TAG, regid);
handler.onSuccess(regid, false);
}
} else { // no play services
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
/**
* Registers the application with GCM servers asynchronously.
* <p>
* Stores the registration ID and app versionCode in the application's
* shared preferences.
*/
private void registerInBackground(final RegistrationCompletedHandler handler) {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getContext());
}
regid = gcm.register(projectNumber);
Log.i(TAG, regid);
// Persist the regID - no need to register again.
storeRegistrationId(getContext(), regid);
} catch (IOException ex) {
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
handler.onFailure("Error :" + ex.getMessage());
}
return regid;
}
#Override
protected void onPostExecute(String regId) {
if (regId != null) {
handler.onSuccess(regId, true);
}
}
}.execute(null, null, null);
}
/**
* Gets the current registration ID for application on GCM service.
* <p>
* If result is empty, the app needs to register.
*
* #return registration ID, or empty string if there is no existing
* registration ID.
*/
public String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
/**
* Stores the registration ID and app versionCode in the application's
* {#code SharedPreferences}.
*
* #param context application's context.
* #param regId registration ID
*/
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
/**
* #return Application's version code from the {#code PackageManager}.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
private SharedPreferences getGCMPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
// how you store the regID in your app is up to you.
return getContext().getSharedPreferences(context.getPackageName(),
Context.MODE_PRIVATE);
}
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
}
return false;
}
return true;
}
private Context getContext() {
return activity;
}
private Activity getActivity() {
return activity;
}
}
Try to set your emulator target to Google API and add a google
account.(add account on emulator: setting->account&sync)

Categories