i need help in storing acces_token and token_type from json object data so i can make the user sesion work ,
every time user logs in, a new token is asigned , i want my acctivity to sync with the token, and when the token dies(expires)take user back to Login, so far i did only sesion management by some string from "String _token_type= "token_type";" and that is a bad result so far ,also i need to somehow post the token and token type to other activity to parse JsonObject by user token,i'm really sorry for my bad english , and maybe for a dumb question ,i'm really desperate i'm tryng to figure it out for 3 days
Json Response when logged
code: 200
error: false
message: "Ok"
data: {
access_token: "585e35343139636330653062613965827"
expires_in: 86400
token_type: "Bearer"
}
Code
package baymd.baymdalpha;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import baymd.baymdalpha.librarys.JSONParser;
public class LoginActivity extends ActionBarActivity implements View.OnClickListener {
private static final String LOGIN_URL = "http://example.com/api/auth";
private static final String TAG_SUCCESS = "code";
private static final String TAG_MESSAGE = "message";
private static final String TAG_DATA="data";
private static final String TAG_TOKEN_TYPE="token_type";
private static final String TAG_TOKEN="access_token";
JSONArray data = null;
JSONParser jsonParser = new JSONParser();
private EditText user, pass;
private Button mSubmit;
private ProgressDialog pDialog;
private String token,token_type;
//Shared preff vars
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String _token = "access_token";
public static final String _token_type= "token_type";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
user = (EditText) findViewById(R.id.inputEmail);
pass = (EditText) findViewById(R.id.inputPass);
mSubmit = (Button) findViewById(R.id.loginBtn);
mSubmit.setOnClickListener(this);
//Shared Prefs Thing
}
protected void onResume(){
sharedpreferences=getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if(sharedpreferences.contains(_token)){
Log.d("LOL",_token);
if(sharedpreferences.contains(_token_type)){
Intent i=new Intent(this,BayTab.class);
startActivity(i);
}
}
super.onResume();
}
#Override
public void onClick(View v) {
new AttemptLogin().execute();
}
class AttemptLogin extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
success = json.getInt(TAG_SUCCESS);
if (success == 200) {
JSONObject c=json.getJSONObject(TAG_DATA);
SharedPreferences.Editor editor=sharedpreferences.edit();
token=c.getString(TAG_TOKEN);
Log.d("TOKENS",token);
token_type=c.getString(TAG_TOKEN_TYPE);
Log.d("TOKENS",token_type);
String u = token;
String p = token_type;
editor.putString(_token,u);
editor.putString(_token_type,p);
Log.d("RESPONSEFROMSHARED.....",_token+" "+u+ "\n"+_token_type+" "+p);
editor.commit();
Log.d("Login Successeful", json.toString());
Intent i = new Intent(LoginActivity.this, BayTab.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
json.getString(TAG_MESSAGE);
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
pDialog.dismiss();
if (s != null) {
Toast.makeText(LoginActivity.this, s, Toast.LENGTH_LONG).show();
}
}
}
}
You should use Google Gson for this.
First create two model classes, one for Session Response and another for the data object. Do as follows:
1. Create the model. Make sure that each class mimics the response keys EXACTLY. Also, make sure that each class has a default constructor as well.
public class SessionResponse {
int code;
String error, message;
Data data;
public SessionResponse(){}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
public class Data {
String access_token, token_type;
int expires_in;
public Data(){}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getToken_type() {
return token_type;
}
public void setToken_type(String token_type) {
this.token_type = token_type;
}
public int getExpires_in() {
return expires_in;
}
public void setExpires_in(int expires_in) {
this.expires_in = expires_in;
}
}
Then use the Google Gson support library to convert the Json to an object. You can then store it to Shared Preferences and get it from any activity. Or even pass it to an activity by string via Intent.
Gson gson = new Gson();
//get the class from JSON
SessionResponse response = gson.fromJson(jsonResponseString, SessionResponse.class);
//convert to String
String jsonResponse = gson.toJson(response);
I hope this is a good start!
Related
Am new to android can any one suggest me, Where am doing wrong?
Whole ManiActiviy.java
Error is 'Method getText must be called from the UI thread, currently inferred thread is worker'
In these 3 line it is giving above error.
person = new Person();
person.setName(etName.getText().toString());
person.setCountry(etCountry.getText().toString());
person.setTwitter(etTwitter.getText().toString());
Class code
import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends Activity implements OnClickListener {
TextView tvIsConnected;
EditText etName, etCountry, etTwitter;
Button btnPost;
Person person;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the views
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
etName = (EditText) findViewById(R.id.etName);
etCountry = (EditText) findViewById(R.id.etCountry);
etTwitter = (EditText) findViewById(R.id.etTwitter);
btnPost = (Button) findViewById(R.id.btnPost);
// check if you are connected or not
if (isConnected()) {
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
} else {
tvIsConnected.setText("You are NOT conncted");
}
// add click listener to Button "POST"
btnPost.setOnClickListener(this);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public static String POST(String url, Person person) {
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", person.getName());
jsonObject.accumulate("country", person.getCountry());
jsonObject.accumulate("twitter", person.getTwitter());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
public boolean isConnected() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnPost:
if (!validate())
Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
break;
}
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http:// http://192.168.0.51:1337/sensormessage/pushSensorData?MAC=18:fe:34:a5:df:8c&OC=0&ALS=3 &POW=100"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
person = new Person();
person.setName(etName.getText().toString());
person.setCountry(etCountry.getText().toString());
person.setTwitter(etTwitter.getText().toString());
return POST(urls[0], person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
private boolean validate() {
if (etName.getText().toString().trim().equals(""))
return false;
else if (etCountry.getText().toString().trim().equals(""))
return false;
else if (etTwitter.getText().toString().trim().equals(""))
return false;
else
return true;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
And Person.java
package android.hmkcode.com.android_post_json;
/**
* Created by HP on 2/2/2017.
*/
public class Person {
private String name;
private String country;
private String twitter;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getTwitter() {
return twitter;
}
public void setTwitter(String twitter) {
this.twitter = twitter;
}
}
Try to pass EditText variables with the class HttpAsyncTask constructor as:
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
EditText etName;
EditText etCountry;
EditText etTwitter;
Context context;
//Constructor to get the values
public HttpAsyncTask(EditText etName, EditText etCountry, EditText etTwitter, Context context){
this.etName = etName;
this.etCountry = etCountry;
this.etTwitter = etTwitter;
this.context = context;
}
#Override
protected String doInBackground(String... urls) {
person = new Person();
person.setName(etName.getText().toString());
person.setCountry(etCountry.getText().toString());
person.setTwitter(etTwitter.getText().toString());
return POST(urls[0], person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, "Data Sent!", Toast.LENGTH_LONG).show();
}
}
And pass editext variables inside as:
new HttpAsyncTask(etName, etCountry, etTwitter, MainActivity.this).execute("http://hmkcode.appspot.com/jsonservlet");
You can't access view in background thread(Worker thread)
you can modify your code like this
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
person = new Person();
person.setName(urls[1]); //name
person.setCountry(urls[2]); //country
person.setTwitter(urls[3]); // twitter
return POST(urls[0], person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
and call like this
new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet",etName.getText().toString(),etCountry.getText().toString(),etTwitter.getText().toString());
Your cannot access the UI component in worker thread(as doInBackground creates a worker thread) unless you use Looper.
Solution 1:
Inside onPreExecute() method you can access ui components as it run in UI thread itself. Do the following
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
Person person;
#Override
protected void onPreExecute(){
person = new Person();
person.setName(etName.getText().toString());
person.setCountry(etCountry.getText().toString());
person.setTwitter(etTwitter.getText().toString());
}
#Override
protected String doInBackground(String... urls) {
return POST(urls[0], person);
}
Solution 2
Just create a Person after onClick and pass the person object in the constructor of the AsynTask()
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnPost:
if (!validate())
Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
person = new Person();
person.setName(etName.getText().toString());
person.setCountry(etCountry.getText().toString());
person.setTwitter(etTwitter.getText().toString());
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask(person).execute("http://hmkcode.appspot.com/jsonservlet");
break;
}
}
And in the constructor you need the following.
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
Person person;
Context context;
//Constructor to get the values
public HttpAsyncTask(Person person, Context context){
this.person= person;
this.context = context;
}
#Override
protected String doInBackground(String... urls) {
return POST(urls[0], person);
}
Hello i think i have done right thing but don't know where i am lagging.Here is my code in which i am starting a service from main activity but service is not started.If anyone know please help me.
MainActivity
package com.example.lalit.gcmtest;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
JsonParser jsonParser = new JsonParser();
String str;
private static final String TAG_SUCCESS = "success";
public static final String NOTIFICATION_URL = "http://kushjalwa.netau.net/tokenStore.php";
public static final String TOKEN_URL = "http://kushjalwa.netau.net/Token_Registration.php";
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private static final String TAG = "MainActivity";
private BroadcastReceiver mRegistrationBroadcastReceiver;
//public ProgressDialog progress;
ProgressDialog pDialog;
static boolean flag=true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (flag) {
Intent intent = new Intent(this, MyRegistrationIntentService.class);
startService(intent);
flag=false;
}
else {
Intent i=getIntent();
str=i.getStringExtra("token");
Log.d("Token in Activity",str);
Log.d("CheckPoint", "check");
new SendingNotification().execute();
}
}
public class SendingNotification extends AsyncTask<String, String, String> {
int success;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("......Registering.......");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args)
{
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("token", str));
Log.d("request!", "heloo");
JSONObject json = jsonParser.makeHttpRequest(TOKEN_URL, "POST", params);
Log.d("Login attempt", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1)
{
Log.d("Login Successful!", json.toString());
}
else
{
Log.d("Sendind Fail", "Fail");
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url)
{
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "Token Stored", Toast.LENGTH_SHORT).show();
}
}
}
Service
package com.example.lalit.gcmtest;
import android.app.IntentService;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MyRegistrationIntentService extends IntentService {
public static String token = null;
private static final String TAG_SUCCESS = "success";
private static final String TAG = "RegIntentService";
public static final String TOKEN_URL = "http://kushjalwa.netau.net/Token_Registration.php";
public static final String NOTIFICATION_URL = "http://kushjalwa.netau.net/ceo.php";
private static final String[] TOPICS = {"global"};
public ProgressDialog pDialog;
Context context;
JsonParser jsonParser = new JsonParser();
public MyRegistrationIntentService() {
super(TAG);
}
#Override
protected void onHandleIntent(Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
try {
synchronized (TAG) {
InstanceID instanceID = InstanceID.getInstance(this);
token = instanceID.getToken("879100952974",
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
// [END get_token]
Log.i(TAG, "GCM Registration Token: " + token);
Intent dialogIntent = new Intent(this, MainActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
dialogIntent.putExtra("token",token);
startActivity(dialogIntent);
sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();
// [END register_for_gcm]
}
} catch (Exception e) {
Log.d(TAG, "Failed to complete token refresh", e);
sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply();
}
Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
}
public class SendingToken extends AsyncTask<String, String, String> {
int success;
/* private ProgressDialog progressDialog = new ProgressDialog(getApplicationContext());
InputStream inputStream = null;
String result = "";
*/
protected void onPreExecute() {
/* progressDialog.setMessage("Your progress dialog message...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
//MyAsyncTask.this.cancel(true);
}
});*/
}
#Override
protected String doInBackground(String... args) {
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("token", token));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(TOKEN_URL, "POST", params);
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
} else {
Log.d("Sendind Fail", "Fail");
}
} catch (Exception ex) {
}
// [END subscribe_topics]
return null;
//}
}
#Override
protected void onPostExecute(String s) {
// pDialog.dismiss();
}
}
}
By Declaring the service in manifest all working fine.
While working on the project i get an error on following Activity.
1. Login.java
on following Line of code.
Line: "String username = user.getText().toString();"
Error: "Method getText() must be called from the UI thread, currently inferred thread is worker."
This is my whole Activity Code.
package com.example.mysqltest;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends Activity implements OnClickListener {
private EditText user, pass;
private Button mSubmit, mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script location:
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/login.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.example.com/webservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
public static String username;
public static String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
//setup input fields
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
//setup buttons
mSubmit = (Button) findViewById(R.id.login);
mRegister = (Button) findViewById(R.id.register);
//register listeners
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
username = user.getText().toString();
password = pass.getText().toString();
new AttemptLogin().execute();
break;
case R.id.register:
Intent i = new Intent(this, Register.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
Intent i = new Intent(Login.this, ReadComments.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
**/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
Unless something has changed that I'm not aware of, that shouldn't be a problem. UI elements can't be updated from the background but accessing their getters has never been an issue.
Anyway, you can get around this by adding a constructor to your AsyncTask which would take the two Strings then send them when creating your task.
private class Login extends AsyncTask<String, String, String>{
// member variables of the task class
String uName, pwd
public AttemptLogin(String userName, String password) {
uName = userName;
pwd = password;
}
#Override
protected String doInBackground(String... args) {...}
and pass them in your onClick()
case R.id.login:
// execute method invokes doInBackground() where we open a Http URL connection using the given Servlet URL
//and get output response from InputStream and return it.
// pass them here
new AttemptLogin(uname.getText().toString(), password.getText().toString()).execute();
break;
i am making a chat application it is working but it is slow. i need a way to make it work faster it reads data from mysql database and displays it..... and i am using asynctask ....
package com.mall.our;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import com.actionbarsherlock.app.SherlockListFragment;
import com.mall.first.JSONParser;
import com.mall.first.Login;
import com.mall.first.MainActivity;
import com.mall.first.R;
public class Chat extends SherlockListFragment {
JSONParser jsonParser = new JSONParser();
private static final String TAG_POSTS = "posts";
public static final String TAG_ID = "id";
public static final String TAG_NAME = "name";
public static final String TAG_pic = "pic";
public static final String TAG_MESSAGE = "message";
public static final String TAG_CATEGORIES_LOGO = "categories_logo";
//user details
private static final String NAME = "name";
private static final String AGE = "age";
private static final String STATUS = "status";
private static final String PIC = "pic";
private static final String SEX = "sex"; String friendname,status;
private static final String TAG_SUCCESS = "success";
//user
private static final String URL = "http://www.thethinker.com.ng/ochat/chattingname.php";
private static final String URL_CATEGORY = "http://www.thethinker.com.ng/ochat/selectchat.php";
private BaseAdapter mAdapter;
private ListView lv;
SharedPreferences sp ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.friends, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new LoadComments().execute();
}
class LoadComments extends AsyncTask<Void, Void, ArrayList<HashMap<String,String>>> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
ArrayList<HashMap<String, String>> categoryList = new ArrayList<HashMap<String, String>>();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
String username = sp.getString("username", "anon");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
JSONObject json = jsonParser.makeHttpRequest(URL_CATEGORY, "POST",
params);
try {
JSONArray categories = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < categories.length(); i++) {
String id = categories.getJSONObject(i).getString("TAG_ID");
String name = categories.getJSONObject(i).getString("TAG_NAME");
String pic = categories.getJSONObject(i).getString("TAG_pic");
String message = categories.getJSONObject(i).getString("TAG_MESSAGE");
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_pic, pic);
map.put(TAG_MESSAGE,message);
categoryList.add(map);
}
}catch (Throwable e){
e.printStackTrace();
}
return categoryList;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
mAdapter = new OtherlistAdapter(getActivity(),result);
setListAdapter(mAdapter);
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
final int position, long id) {
class loginAccess extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
int success;
#SuppressWarnings("unchecked")
HashMap<String, String> name =
(HashMap<String, String>) mAdapter.getItem(position);
String n=name.get(TAG_NAME);
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", n));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(URL, "POST",
params);
Log.d("Login attempt", json.toString());
String sex=json.getString(SEX);
String age=json.getString(AGE);
String pic=json.getString(PIC);
String statuss = json.getString(STATUS);
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
Editor edit = sp.edit();
edit.putString("value", n);
edit.putString("sex", sex);
edit.putString("age", age);
edit.putString("pic", pic);
edit.putString("statuss", statuss);
edit.commit();
Intent i = new Intent(getActivity(),Chatting.class);
startActivity(i);
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
new loginAccess().execute();
}
});
}
}
}
as you can see te second asynctask is in the postexecute of the first asynctask...it is meant to take the username of the user in to the next class called "CHATTING.java"....... at first when is click it goes to "chatting.java" class a bit slowly........ but when i go back to chat.java class and try to go back to "chatting.java"... it just get too slow
Below is chatting.java class....
package com.mall.our;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.mall.first.JSONParser;
import com.mall.first.MessageCategoryList;
import com.mall.first.R;
import com.mall.our.Chat.LoadComments;
import android.app.ListActivity;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Chatting extends ListActivity {
// fr the sending of message
private static final String TAG_POSTS = "posts";
public static final String TAG_ID = "id";
public static final String TAG_time = "time";
public static final String TAG_state = "state";
public static final String TAG_MESSAGE = "categories_message";
public static final String TAG_CATEGORIES_LOGO = "categories_logo";
public static final String TAG_from = "from ";
//end
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String URL_CATEGORY = "http://www.thethinker.com.ng/ochat/selectmess.php";
private static final String url = "http://www.thethinker.com.ng/ochat/sendmessage.php";
private static final String ur = "http://www.thethinker.com.ng/ochat/seen.php";
private BaseAdapter mAdapter;
EditText mess;
private ListView lv;
ImageButton send;
private static final String TAG_SUCCESS = "success";
Intent b = getIntent();
String state;
int flag = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.yon);
mess = (EditText) findViewById(R.id.mess);
send = (ImageButton) findViewById(R.id.send);
lv = getListView();
lv.setDivider(null);
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long arg3) {
Toast.makeText(Chatting.this, "Item selected: " + position,
Toast.LENGTH_LONG).show();
}
});
final Handler ham = new Handler();
Runnable race = new Runnable() {
#Override
public void run() {
new LoadComments().execute();
ham.postDelayed(this, 1 * 1000);
}
};
ham.postDelayed(race, 1 * 1000);
ff();
sending();
}
private void sending() {
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (!isOnline(Chatting.this)) {
Toast.makeText(Chatting.this, "No network connection",
Toast.LENGTH_LONG).show();
return;
}
new sendtext().execute();
}
private boolean isOnline(Context mContext) {
ConnectivityManager cm = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
});
}
public void ff(){
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Chatting.this);
String friendname = sp.getString("value", "anon");
String sta = sp.getString("statuss", "anon");
TextView name = (TextView) findViewById(R.id.user);
TextView stat = (TextView) findViewById(R.id.status);
name.setText(friendname);
stat.setText(sta);
}
class LoadComments extends
AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
private ProgressDialog pDialog;
int priorPosition= getListView().getFirstVisiblePosition();
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Chatting.this);
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
Void... arg0) {
int successr;
ArrayList<HashMap<String, String>> categoryList = new ArrayList<HashMap<String, String>>();
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Chatting.this);
String friend = sp.getString("value", "anon");
String username = sp.getString("username", "anon");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("friend", friend));
JSONObject json = jsonParser.makeHttpRequest(URL_CATEGORY, "POST",
params);
try {
List<NameValuePair> seen = new ArrayList<NameValuePair>();
seen.add(new BasicNameValuePair("username", username));
seen.add(new BasicNameValuePair("friend", friend));
successr = json.getInt(TAG_SUCCESS);
JSONArray categories = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < categories.length(); i++) {
String id = categories.getJSONObject(i).getString("TAG_ID");
String time = categories.getJSONObject(i).getString(
"TAG_time");
String songs_count = categories.getJSONObject(i).getString(
"TAG_CATEGORIES_COUNT");
String from = categories.getJSONObject(i).getString(
"TAG_from");
state = categories.getJSONObject(i).getString(
"TAG_state");
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_time, time);
map.put(TAG_MESSAGE, songs_count);
map.put(TAG_from, from);
map.put(TAG_state, state);
categoryList.add(map);
}
} catch (Throwable e) {
e.printStackTrace();
}
return categoryList;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
mAdapter = new MessageCategoryList(Chatting.this,result);
lv.setAdapter(mAdapter);
getListView().setSelection(priorPosition);
}
}
class sendtext extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Chatting.this);
pDialog.setMessage("posting...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Chatting.this);
String post_username = sp.getString("username", "anon");
String friendname = sp.getString("value", "anon");
String picc = sp.getString("pic", "anon");
String message = mess.getText().toString();
params.add(new BasicNameValuePair("from", post_username));
params.add(new BasicNameValuePair("message", message));
params.add(new BasicNameValuePair("to", friendname));
params.add(new BasicNameValuePair("pic", picc));
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
if (flag == 1)
Toast.makeText(Chatting.this, " saved", Toast.LENGTH_LONG)
.show();
mess.setText("");
}
}
}
Make the following optimizations:
cache frequently used data, so you do not have to query for it from a large table
add indexes to the fields you are searching for
archive old, rarely used data to archive tables
make sure your queries are optimal and you are merging whatever is possible without raising the complexity of your queries
you are trying a chat application with asynchrone connection , i think it's not good like idea , i advice you to use WebSocket for connection in real-time (synchrone connection), you can find a many examples which use use websocket for chat application like this : http://www.androidhive.info/2014/10/android-building-group-chat-app-using-sockets-part-1/
- you need implement a server side
- then your application ..
I hope you like this approach
This is my code,it gets detail from previous activity:it get two values as location and bloodGroup and SearchDonor will get it and process it.
Intent intent =getIntent();
location = intent.getStringExtra("location");
bloodgroup = intent.getStringExtra("bloodgroup");
so iget an when i write it in doBackGround process,i want to add above code in following code
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class SearchDonor extends ListActivity {
private Context context;
private static String url = "http://10.0.2.2/bl/getDonor.php";
private static final String TAG_FIRSTNAME = "FirstName";
private static final String TAG_MIDDLENAME = "MiddleName";
private static final String TAG_LASTNAME = "LastName";
private static final String TAG_ADDRESS = "Address";
private static final String TAG_CELLPHONE = "CellPhone";
private static final String TAG_DONORS = "donors";
private static final String TAG_SUCCESS = "success";
private static final String TAG_DONORID = "Donor_ID";
private static final String TAG_LOCATION = "location";
private static final String TAG_BLOODGROUP = "bloodgroup";
JSONArray donors = null;
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_donor);
new ProgressTask(SearchDonor.this).execute();
}
#Override
protected void onListItemClick(ListView l,View v,int position,long id)
{
Intent intent = new Intent(this,DonorDetails.class);
String did=( (TextView)v.findViewById(R.id.donorId)).getText().toString();
String Name=( (TextView)v.findViewById(R.id.vehicleType)).getText().toString();
String Address=( (TextView)v.findViewById(R.id.vehicleColor)).getText().toString();
String cellphone=( (TextView)v.findViewById(R.id.fuel)).getText().toString();
intent.putExtra("did", did);
intent.putExtra("Name", Name);
intent.putExtra("Address", Address);
intent.putExtra("cellPhone", cellphone);
startActivity(intent);
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
private ListActivity activity;
// private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.setIndeterminate(false);
this.dialog.setCancelable(false);
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.list_item, new String[] { TAG_DONORID,TAG_FIRSTNAME , TAG_ADDRESS,
TAG_CELLPHONE }, new int[] {
R.id.donorId,R.id.vehicleType, R.id.vehicleColor, R.id.fuel });
setListAdapter(adapter);
// selecting single ListView item
lv = getListView();
}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
List<NameValuePair>params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_LOCATION,location));
params.add(new BasicNameValuePair(TAG_BLOODGROUP,bloodgroup));
JSONObject json = jParser.makeHttpRequest(url,"GET",params);
// getting JSON string from URL
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
donors = json.getJSONArray(TAG_DONORS);
// looping through All Products
for (int i = 0; i < donors.length(); i++) {
JSONObject c = donors.getJSONObject(i);
String donoID = c.getString(TAG_DONORID);
String firstName = c.getString(TAG_FIRSTNAME );
String middleName = c.getString(TAG_MIDDLENAME );
String lastName = c.getString(TAG_LASTNAME );
String address = c.getString(TAG_ADDRESS );
String cellPhone = c.getString(TAG_CELLPHONE );
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_DONORID, donoID);
// adding each child node to HashMap key => value
map.put(TAG_FIRSTNAME, firstName);
map.put(TAG_MIDDLENAME, middleName);
map.put(TAG_LASTNAME ,lastName);
map.put(TAG_ADDRESS, address);
map.put(TAG_CELLPHONE, cellPhone);
jsonlist.add(map);
}
}
else{
String message ="No Donor Found";
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_FIRSTNAME, message);
map.put(TAG_MIDDLENAME, "");
map.put(TAG_LASTNAME ,"");
map.put(TAG_ADDRESS,"");
map.put(TAG_CELLPHONE, "");
jsonlist.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}
You can pass both values (comma separated or as array) in execute() method, and these values will be available in doInBackground() method.
Code:
// Calling AsyncTask in onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_donor);
Intent i = getIntent();
if(i!=null) {
location = intent.getStringExtra("location");
bloodgroup = intent.getStringExtra("bloodgroup");
new ProgressTask(SearchDonor.this).execute(location,bloodgroup);
}
}
private class myAsyncTask extends AsyncTask<String, String, String> {
#Override
protected Void doInBackground(String...params)
{
// Getting values from params
String location = params[0];
String bloodGroup= params[1];
....
}
I did not run the code but it will give you the idea for doing. If you get any error post here.