Not able to call Service from Activity - android

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.

Related

Converting DefaultHttpClient to HttpUrlConnection

Hello guys so i'm having difficult in changing this classes that i've created to httpurlConnection. i've seraced the web and im not familiar at all with the httpUrlConnection
App flow:
coming to MainActivity => OnTokenAcuired => GetCokie => Auth
then i have an httpPostRequest
MainActivity:
package com.ap2.demo.comunication;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import com.ap2.demo.R;
import com.ap2.demo.general.SplashActivity;
import org.apache.http.impl.client.DefaultHttpClient;
import java.util.ArrayList;
public class MainActivity extends Activity {
AccountManager accountManager;
private Account[] accounts;
Spinner spinner;
public static DefaultHttpClient httpClient = new DefaultHttpClient();
Account account;
public static String email = "";
ImageView img;
public static boolean enteredOnce = false;
public static String uniqueIDPhone = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
accountManager = AccountManager.get(getApplicationContext());
// assembling all gmail accounts
accounts = accountManager.getAccountsByType("com.google");
// add all gmail accounts :
ArrayList<String> accountList = new ArrayList<String>();
for (Account account : accounts) {
accountList.add(account.name);
}
// setting spinner to be viewed
spinner = (Spinner) findViewById(R.id.account);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, accountList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
img = (ImageView) findViewById(R.id.splash_door);
//Button startAuth = (Button) findViewById(R.id.startAuth);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinner = (Spinner) findViewById(R.id.account);
account = accounts[spinner.getSelectedItemPosition()];
email = account.name;
// getIntent().putExtra("task", 1);
accountManager.getAuthToken(account, "ah", null, false,
new OnTokenAcquired(httpClient, MainActivity.this), null);
Intent intent = new Intent(MainActivity.this, SplashActivity.class);
startActivity(intent);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
accountManager.getAuthToken(account, "ah", null, false,
new OnTokenAcquired(httpClient, MainActivity.this), null);
}
else if(resultCode == RESULT_CANCELED){
// user canceled
}
}
}
OnTokenAcquired:
package com.ap2.demo.comunication;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.ap2.demo.enumPackage.Constants;
import org.apache.http.impl.client.DefaultHttpClient;
/**
* Created by Daniel on 19-Jun-15.
*/
/*the result for the auth token request is returned to your application
via the Account Manager Callback you specified when making the request.
check the returned bundle if an Intent is stored against the AccountManager.KEY_INTENT key.
if there is an Intent then start the activity using that intent to ask for user permission
otherwise you can retrieve the auth token from the bundle.*/
public class OnTokenAcquired implements AccountManagerCallback<Bundle> {
private static final int USER_PERMISSION = 989;
private DefaultHttpClient httpclient;
Activity activity;
public OnTokenAcquired(DefaultHttpClient httpclient, Activity activity)
{
this.httpclient = httpclient;
this.activity = activity;
}
#Override
public void run(AccountManagerFuture<Bundle> result) {
Bundle bundle;
try {
bundle = (Bundle) result.getResult();
if (bundle.containsKey(AccountManager.KEY_INTENT)) {
Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivityForResult(intent, USER_PERMISSION);
} else {
setAuthToken(bundle);
}
}
catch(Exception e){
e.printStackTrace();
}
}
//using the auth token and ask for a auth cookie
protected void setAuthToken(Bundle bundle) {
String authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
new GetCookie(httpclient, Constants.SERVER_REQUESTS.MY_APP_ID, activity.getBaseContext()).execute(authToken);
}
}
package com.ap2.demo.comunication;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import com.ap2.demo.enumPackage.Constants;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import java.io.ByteArrayOutputStream;
/**
* Created by Daniel on 19-Jun-15.
*/
public class GetCookie extends AsyncTask<String, Void, Boolean> {
String appId;
HttpParams params;
private HttpResponse response;
Context context;
private DefaultHttpClient httpclient;
public GetCookie(DefaultHttpClient httpclient, String appId, Context context)
{
this.httpclient = httpclient;
params = httpclient.getParams();
this.appId = appId;
this.context = context;
}
protected Boolean doInBackground(String... tokens) {
try {
// Don't follow redirects
params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
HttpGet httpGet = new HttpGet("http://" + appId
+ ".appspot.com/_ah/login?continue=http://" + appId + ".appspot.com/&auth=" + tokens[0]);
response = httpclient.execute(httpGet);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
if(response.getStatusLine().getStatusCode() != 302){
// Response should be a redirect
return false;
}
//check if we received the ACSID or the SACSID cookie, depends on http or https request
for(Cookie cookie : httpclient.getCookieStore().getCookies()) {
if(cookie.getName().equals("ACSID") || cookie.getName().equals("SACSID")){
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
cancel(true);
} finally {
params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
}
return false;
}
protected void onPostExecute(Boolean result)
{
new Auth(httpclient, context).execute(Constants.SERVER_REQUESTS.LOGIN);
}
}
package com.ap2.demo.comunication;
import android.content.Context;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;
import android.widget.Toast;
import com.ap2.demo.R;
import com.ap2.demo.enumPackage.Constants;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
/**
* Created by Daniel on 19-Jun-15.
*/
public class Auth extends AsyncTask<String, Void, Boolean> {
private DefaultHttpClient httpclient;
private HttpResponse response;
private String content = null;
Context context;
public Auth(DefaultHttpClient httpclient, Context context)
{
this.httpclient = httpclient;
this.context = context;
}
protected Boolean doInBackground(String... urls) {
try {
HttpGet httpGet = new HttpGet(urls[0]);
response = httpclient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
content = out.toString();
return true;
}
} catch (Exception e) {
e.printStackTrace();
cancel(true);
}
return false;
}
//display the response from the request above
protected void onPostExecute(Boolean result) {
if (content != null) {
try {
System.out.print(result);
JSONObject obj = new JSONObject(content);
String status = obj.getString(Constants.LOGIN_SERVICE.STATUS);
if (status.equals(Constants.LOGIN_SERVICE.LOGIN_STATUS_OF_USER)) {
Toast.makeText(context, R.string.user_already_logged_in_status,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, R.string.welcome_message,
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(context, R.string.failed_to_login + content,
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, R.string.could_not_loged_to_server,
Toast.LENGTH_LONG).show();
}
}
}
now notice im using the same httpclient because of the auth and cockie:
package com.ap2.demo.channels;
import android.app.Activity;
import android.os.AsyncTask;
import com.ap2.demo.comunication.MainActivity;
import com.ap2.demo.enumPackage.Constants;
import com.ap2.demo.main_activity.MapWithMarkers;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Daniel on 30-Jun-15.
*/
public class ServerRequestAddChannel extends AsyncTask<String, String, String> {
Activity activity;
String name;
public ServerRequestAddChannel(Activity activity, String name) {
this.activity = activity;
this.name = name;
}
#Override
protected String doInBackground(String... params) {
HttpPost httppost = new HttpPost(params[0]);
try {
// i have name and path only left id
int idCounter = MapWithMarkers.id_counter++;
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
String name_of_channel = name;
if (name.equals(Constants.REVIEWS_CHANNEL.NAME)) {
// add special id to reviews channel
nameValuePairs.add(new BasicNameValuePair(Constants.REVIEWS_CHANNEL.ID, Constants.REVIEWS_CHANNEL.ID));
} else {
name_of_channel = name + Integer.toString(idCounter);
// taking off all free space for unique id
name_of_channel = name_of_channel.replaceAll(" ","");
nameValuePairs.add(new BasicNameValuePair(Constants.CHANNEL_REQUESTS.CHANNEL_TAG_ID, name_of_channel));
}
nameValuePairs.add(new BasicNameValuePair(Constants.CHANNEL_REQUESTS.CHANNEL_TAG_NAME, name));
nameValuePairs.add(new BasicNameValuePair(Constants.CHANNEL_REQUESTS.CHANNEL_TAG_ICON, ""));
// adding the channel to my new list
if (!name_of_channel.equals(Constants.REVIEWS_CHANNEL.NAME)) {
MapWithMarkers.channels_map.put(name_of_channel, new ChannelItem(name_of_channel, "", name));
MapWithMarkers.my_subscriptions.add(name_of_channel);
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = MainActivity.httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
String text = getASCIIContentFromEntity(entity);
return response.getStatusLine().getReasonPhrase().toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
protected void onPostExecute(String result) {
((AddChannelActivity) activity).moveToNextIntent();
}
protected String getASCIIContentFromEntity(HttpEntity entity)
throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
return out.toString();
}
}
please help..

make asynctask run faster

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

I want to pass some argument get from intent to doBackground

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.

Android Token save from json api

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!

error posting data to webservice

I want to post data using JSON. But i am not able to achieve this.
This is my java code:
package com.bandapp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class UpcomingShow extends ListActivity {
public static final String TAG_SHOW_TITLE = "show_title";
public static final String TAG_SHOW_VENUE = "show_venue";
public static final String TAG_SHOW_DATE = "show_date";
public static final String TAG_SHOW_TIME = "show_time";
public static String URL = "http://example.com/example/example/mainAPI.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upcoming_show);
new AsyncData().execute();
}
class AsyncData extends AsyncTask<String, Void, Void> {
JSONParser jParser;
ArrayList<HashMap<String, String>> upcomingShows;
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(UpcomingShow.this);
pDialog.setTitle("Loading....");
pDialog.setMessage("Please wait...");
pDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... args) {
// TODO Auto-generated method stub
jParser = new JSONParser();
List<NameValuePair> params = new ArrayList<NameValuePair>();
upcomingShows = new ArrayList<HashMap<String,String>>();
params.add(new BasicNameValuePair("rquest", "={"));
params.add(new BasicNameValuePair("method","band_info"));
params.add(new BasicNameValuePair("body","[{}]}"));
String res = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
res = EntityUtils.toString(response.getEntity());
JSONTokener t = new JSONTokener(res);
JSONArray a = new JSONArray(t);
JSONObject o = a.getJSONObject(0);
String sc = o.getString(TAG_SHOW_TITLE);
if(sc.equals("1"))
{
// posted successfully
Toast.makeText(UpcomingShow.this, sc, Toast.LENGTH_SHORT).show();
}
else
{
// error occurred
Toast.makeText(UpcomingShow.this, "Fail.", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(UpcomingShow.this, upcomingShows, R.layout.upcomingshows_row, new String[] {
TAG_SHOW_TITLE, TAG_SHOW_DATE, TAG_SHOW_TIME, TAG_SHOW_VENUE }, new int[] { R.id.textTitle, R.id.textdate,
R.id.textTime, R.id.textVenue });
setListAdapter(adapter);
}
}
}
Also i am not able to Toast any of the message that i have kept in doInBackground(). Can you please help me solving this please...
You can't toast into doInBackground() because you can't update the UIview during the thread execution ! You should to use 'onProgress' and 'publishProgress'
change :
class AsyncData extends AsyncTask<String, Void, Void>
to:
class AsyncData extends AsyncTask<String, String, Void>
and override onProgress for toast:
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
if (values[0] != null)
Toast.makeText(UpcomingShow.this, values[0], Toast.LENGTH_SHORT).show();
}
And into doInBackground():
if(sc.equals("1"))
{
publishProgress(sc);
}
else
{
publishProgress("Fail.");
}
if(sc.equals("1"))
{
// posted successfully
Toast.makeText(UpcomingShow.this, sc, Toast.LENGTH_SHORT).show();
}
else
{
// error occurred
Toast.makeText(UpcomingShow.this, "Fail.", Toast.LENGTH_SHORT).show();
}
Remove this code form doInBackground
You can not update your UI on do in background , you can get result in onPostExecute and able to pop up those toast .
I tried sending a post your request through Postman(google extension) and the URL you've provided responded with HTTP Status 200 but without a response message. Problem is, based on the code provided, is that you're expecting a message response from the said url. You should probably check with the server you are connecting with.
While doing AsyncTask<String, Void, Void> Task you can’t achieve Toast display in Main thread, user Log.d(“TAG”,”your-text”);
You can achieve Toast in onPostExecution()
}catch (Exception e)
{
e.printStackTrace();
}
return sc;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
if(result.equals("1"))
{
// posted successfully
Toast.makeText(UpcomingShow.this, result, Toast.LENGTH_SHORT).show();
}
else
{
// error occurred
Toast.makeText(UpcomingShow.this, "Fail.", Toast.LENGTH_SHORT).show();
}
}
}

Categories

Resources