make asynctask run faster - android

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

Related

Not able to call Service from Activity

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.

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.

Show listview picture and details using picasso

i am try to display and image in listview in android and it is not showing i have beening trying it for a while now. i have a database and i have put in url or images thier name and id .. and i want the listview to show the images and thier detail.
but it is giving me errors ... can anyone help me..
it is telling me category not found..
package com.example.cann;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class CategoryActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// ALL JSON node names
private static final String TAG_POSTS = "posts";
public static final String TAG_ID = "id";
public static final String TAG_NAME = "category";
public static final String TAG_CATEGORIES_COUNT = "categories_count";
public static final String TAG_CATEGORIES_LOGO = "categories_logo";
private static final String URL_CATEGORY = "http://10.0.2.2/music/selectm.php";
// albums JSONArray
JSONArray categories = null;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// private ListView lv;
private BaseAdapter mAdapter;
ArrayList<HashMap<String, String>> categoryList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category);
// Hashmap for ListView
categoryList = new ArrayList<HashMap<String, String>>();
Log.d("onCreate: ", "Yep");
new LoadComments().execute();
}
public void yess(){
// get listview
ListView 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(CategoryActivity.this, "Item selected: " + position,
Toast.LENGTH_LONG).show();
// Uncomment this to start a new Activity for a chosen item
/* Intent i = new Intent(getApplicationContext(),
ItemListActivity.class);
String category_id = ((TextView) view
.findViewById(R.id.category_id)).getText()
.toString();
i.putExtra("category_id", category_id);
startActivity(i);*/
}
});
}
public void upd(){
categoryList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(URL_CATEGORY);
try {
categories = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < categories.length(); i++) {
JSONObject c =categories.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String songs_count = c.getString(TAG_CATEGORIES_COUNT);
String category_logo = c.getString(TAG_CATEGORIES_LOGO);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_CATEGORIES_COUNT, songs_count);
map.put(TAG_CATEGORIES_LOGO, category_logo);
categoryList.add(map);
// adding HashList to ArrayList
}
mAdapter = new CategoryListAdapter(CategoryActivity.this,
categoryList);
getListView().setAdapter(mAdapter);
// dismiss the dialog after getting all albums
pDialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CategoryActivity.this);
pDialog.setMessage("Loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
upd();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
public void run() {
pDialog.dismiss();
yess();
}
});
}
}
}
package com.example.cann;
import java.util.ArrayList;
import java.util.HashMap;
import com.squareup.picasso.Picasso;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CategoryListAdapter extends BaseAdapter {
private Context mContext;
LayoutInflater inflater;
private final ArrayList<HashMap<String, String>> urls;
HashMap<String, String> resultp = new HashMap<String, String>();
public static final String CATEGORY_LOGO_URL = "http://10.0.2.2/demi.jpg";
public CategoryListAdapter(Context context,
ArrayList<HashMap<String, String>> items) {
mContext = context;
urls = items;
}
#Override
public int getCount() {
return urls.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return getItem(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView category_name;
ImageView category_logo;
TextView item_count;
TextView item_id;
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_list_category, parent,
false);
resultp = urls.get(position);
category_name = (TextView) view.findViewById(R.id.category_name);
category_logo = (ImageView) view.findViewById(R.id.img_category_logo);
item_count = (TextView) view.findViewById(R.id.songs_count);
item_id = (TextView) view.findViewById(R.id.category_id);
category_name.setText(resultp.get(CategoryActivity.TAG_NAME));
item_count.setText(resultp.get(CategoryActivity.TAG_CATEGORIES_COUNT));
item_id.setText(resultp.get(CategoryActivity.TAG_ID));
// Picasso image loader library starts here
Picasso.with(mContext)
.load(CATEGORY_LOGO_URL
+ resultp.get(CategoryActivity.TAG_CATEGORIES_LOGO)) // Photo URL
.placeholder(R.drawable.placeholder) // This image will be displayed while photo URL is loading
.error(R.drawable.error) // if error shows up during downloading
.fit().centerCrop() // settings
.into(category_logo); // we put it into our layout component (imageview)
return view;
}
}
and i have tested my php script and it is displaying image
require("config.inc.php");
$query = "Select * FROM music";
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["TAG_ID"] = $row["id"];
$post[" TAG_NAME"] = $row["Artist"];
$post["TAG_CATEGORIES_COUNT"] = $row["Song"];
$post["TAG_CATEGORIES_LOGO"] = $row["Artpics"];
array_push($response["posts"], $post);
}
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Post Available!";
die(json_encode($response));
}
?>
my Logcat
09-13 07:38:59.020: W/System.err(1315): org.json.JSONException: No value for id
09-13 07:38:59.220: W/System.err(1315): at org.json.JSONObject.get(JSONObject.java:355)
09-13 07:38:59.220: W/System.err(1315): at org.json.JSONObject.getString(JSONObject.java:515)
09-13 07:38:59.260: W/System.err(1315): at com.example.cann.CategoryActivity.upd(CategoryActivity.java:103)
09-13 07:38:59.260: W/System.err(1315): at com.example.cann.CategoryActivity$LoadComments.doInBackground(CategoryActivity.java:148)
09-13 07:38:59.270: W/System.err(1315): at com.example.cann.CategoryActivity$LoadComments.doInBackground(CategoryActivity.java:1)
09-13 07:38:59.270: W/System.err(1315): at android.os.AsyncTask$2.call(AsyncTask.java:288)
09-13 07:38:59.270: W/System.err(1315): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
09-13 07:38:59.270: W/System.err(1315): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
09-13 07:38:59.270: W/System.err(1315): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
09-13 07:38:59.270: W/System.err(1315): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
09-13 07:38:59.270: W/System.err(1315): at java.lang.Thread.run(Thread.java:841)
Try to replace this peace of code :
String id = c.getString("TAG_ID");
String name = c.getString("TAG_NAME");
String songs_count = c.getString("TAG_CATEGORIES_COUNT");
String category_logo = c.getString("TAG_CATEGORIES_LOGO");
Also remove space from this :
$post[" TAG_NAME"] replace to $post["TAG_NAME"]
Note : your using wrong key to get data from json.
public class CategoryActivity extends ListActivity {
private static final String TAG_POSTS = "posts";
public static final String TAG_ID = "id";
public static final String TAG_NAME = "category";
public static final String TAG_CATEGORIES_COUNT = "categories_count";
public static final String TAG_CATEGORIES_LOGO = "categories_logo";
private static final String URL_CATEGORY = "http://10.0.2.2/music/selectm.php";
private BaseAdapter mAdapter;
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category);
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(CategoryActivity.this, "Item selected: " + position,
Toast.LENGTH_LONG).show();
// Uncomment this to start a new Activity for a chosen item
/* Intent i = new Intent(getApplicationContext(),
ItemListActivity.class);
String category_id = ((TextView) view
.findViewById(R.id.category_id)).getText()
.toString();
i.putExtra("category_id", category_id);
startActivity(i);*/
}
});
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(CategoryActivity.this);
pDialog.setMessage("Loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
ArrayList<HashMap<String, String>> categoryList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(URL_CATEGORY);
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 songs_count = categories.getJSONObject(i).getString("TAG_CATEGORIES_COUNT");
String category_logo = categories.getJSONObject(i).getString("TAG_CATEGORIES_LOGO");
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_CATEGORIES_COUNT, songs_count);
map.put(TAG_CATEGORIES_LOGO, category_logo);
categoryList.add(map);
}
}catch (Throwable e){
e.printStackTrace();
}
return categoryList;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
if(pDialog.isShowing()){
pDialog.dismiss();
}
mAdapter = new CategoryListAdapter(CategoryActivity.this,result);
lv.setAdapter(mAdapter);
}
}
}

How to make the TTS to read all the Listview items by clicking it only once?

I have a Listview in android that can be read by TTS when you click the items it reads it, but my problem is how to make the TTS to read all the items by clicking any of the items in the listview only once?
here's the codes
package learn2crack.listview;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONArray;
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.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import learn2crack.listview.library.JSONParser;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener {
ListView list;
TextView html;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=New%20York,NY&sensor=false"; //url is just a sample
//JSON Node Names
private static final String TAG_OS = "routes";
private static final String TAG_HTM = "html_instructions";
private TextToSpeech myTTS;
private int MY_DATA_CHECK_CODE = 0;
JSONArray android = null;
public void onInit(int initStatus) {
// check for successful instantiation
if (initStatus == TextToSpeech.SUCCESS) {
if (myTTS.isLanguageAvailable(Locale.US) == TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.US);
} else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
html = (TextView) findViewById(R.id.html_instruction);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for (int x = 0; x < android.length(); x++) {
JSONArray legs = android.getJSONObject(x).getJSONArray("legs");
JSONObject distance = legs.getJSONObject(0).getJSONObject("distance");
JSONObject duration = legs.getJSONObject(0).getJSONObject("duration");
JSONArray steps = legs.getJSONObject(0).getJSONArray("steps");
for (int j = 0; j < steps.length(); j++) {
String html_instructions = steps.getJSONObject(j).getString("html_instructions");
String s = html_instructions.replaceAll("<(\"[^\"]*\"|'[^']*'|[^'\">])*>", " ");
//for(int i = 0; i < android.length(); i++){
//JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
//String ver = c.getString(TAG_VER);
//String name = c.getString(TAG_NAME);
//String api = c.getString(TAG_API);
//String htm = c.getString("html_instructions");
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_HTM, s);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
final ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] {TAG_HTM}, new int [] {R.id.html_instruction});
list.setAdapter(adapter);
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("html"), Toast.LENGTH_SHORT).show();
parent.getAdapter();
//adapter.getItem(position).toString();
String words = adapter.getItem(position).toString();
// String words = html.getText().toString();
speakWords(words);
}
private void speakWords(String speech) {
//speak straight away
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
});
}
}} catch (JSONException e) {
e.printStackTrace();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
//the user has the necessary data - create the TTS
myTTS = new TextToSpeech(this,(OnInitListener) this);
}
else {
//no data - install it now
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
}
}

onResume() method on list view activity

I am working trying to solve an issue on an activity, but I am not able to find the reason for the behaviour.
I have a list view activity (Activity A), if the app user taps on a list row, a second list view activity (Activity B) is shown and all expected list objects are on the list.
Then, if the user navigates from activity B back to activity A, and selects the same or another row, then activity B is shown again, but none object is shown on the list.
I was told by another SO user to include a onResume method. I have done it, but the issue is not solved.
Here you have the activity B code:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
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.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 ofertas_list extends ListActivity {
private ProgressDialog pDialog;
// JSON node keys
private static final String TAG_NAME = "nombreCategoria";
private static final String TAG_ID = "idCategoria";
private static final String TAG_CATEGORIAS = "Categorias";
// URL to get contacts JSON
private static String url = "http://xxxxx/android_ofertaslist.php?id=";
// JSON Node names
private static final String TAG_NOMBREEMPRESA = "nombreEmpresa";
private static final String TAG_IDEMPRESA = "idEmpresa";
private static final String TAG_DESCRIPCIONEMPRESA = "descripcionEmpresa";
private static final String TAG_STRIMAGEN = "strImagen";
private static final String TAG_DIRECCIONEMPRESA = "direccionEmpresa";
private static final String TAG_TELEFONOEMPRESA = "telefonoEmpresa";
private static final String TAG_FACEBOOKEMPRESA = "facebookEmpresa";
private static final String TAG_EMAILEMPRESA = "emailEmpresa";
private static final String TAG_TEXTOOFERTA = "textoOferta";
private static final String TAG_HORARIOEMPRESA = "horarioEmpresa";
private static final String TAG_CATEGORIAEMPRESA = "categoriaEmpresa";
private static final String TAG_LATITUDEMPRESA = "latitudEmpresa";
private static final String TAG_LONGITUDEMPRESA = "longitudEmpresa";
private static final String TAG_VALORACIONEMPRESA = "valoracionEmpresa";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onResume(){
super.onResume();
new GetContacts().execute();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categorias);
// getting intent data
Intent in = getIntent();
// JSON node keys
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String email = in.getStringExtra(TAG_ID);
// URL to get contacts JSON
this.url = url+email;
this.setTitle(name);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
//cambiar por los nuevos campos
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
//Starting single contact activity
//cambiar por los nuevos campos
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_ID, cost);
startActivity(in);
}
});
// Calling async task to get json
//new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ofertas_list.this);
pDialog.setMessage("Cargando datos...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CATEGORIAS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String nombreEmpresa = c.getString(TAG_NOMBREEMPRESA);
String descripcionEmpresa = c.getString(TAG_DESCRIPCIONEMPRESA);
String strImagen = c.getString(TAG_STRIMAGEN);
String direccionEmpresa = c.getString(TAG_DIRECCIONEMPRESA);
String telefonoEmpresa = c.getString(TAG_TELEFONOEMPRESA);
String facebookEmpresa = c.getString(TAG_FACEBOOKEMPRESA);
String emailEmpresa = c.getString(TAG_EMAILEMPRESA);
String textoOferta = c.getString(TAG_TEXTOOFERTA);
String horarioEmpresa = c.getString(TAG_HORARIOEMPRESA);
String categoriaEmpresa = c.getString(TAG_CATEGORIAEMPRESA);
String valoracionEmpresa = c.getString(TAG_VALORACIONEMPRESA);
String latitudEmpresa = c.getString(TAG_LATITUDEMPRESA);
String longitudEmpresa = c.getString(TAG_LONGITUDEMPRESA);
String idEmpresa = c.getString(TAG_IDEMPRESA);
// Phone node is JSON Object
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_IDEMPRESA, idEmpresa);
contact.put(TAG_NOMBREEMPRESA, nombreEmpresa);
contact.put(TAG_DESCRIPCIONEMPRESA,descripcionEmpresa);
contact.put(TAG_STRIMAGEN,strImagen);
contact.put(TAG_DIRECCIONEMPRESA,direccionEmpresa);
contact.put(TAG_TELEFONOEMPRESA,telefonoEmpresa);
contact.put(TAG_FACEBOOKEMPRESA,facebookEmpresa);
contact.put(TAG_EMAILEMPRESA,emailEmpresa);
contact.put(TAG_TEXTOOFERTA,textoOferta);
contact.put(TAG_HORARIOEMPRESA,horarioEmpresa);
contact.put(TAG_CATEGORIAEMPRESA,categoriaEmpresa);
contact.put(TAG_VALORACIONEMPRESA,valoracionEmpresa);
contact.put(TAG_LATITUDEMPRESA,latitudEmpresa);
contact.put(TAG_LONGITUDEMPRESA,longitudEmpresa);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ofertas_list.this, contactList,
R.layout.list_item_ofertas, new String[] { TAG_NOMBREEMPRESA, TAG_DIRECCIONEMPRESA}, new int[] { R.id.name,
R.id.email });
setListAdapter(adapter);
}
}
}
I am trying to solve the issue for two days but still no success. Please you are kindly requested to give me an advice on how to solve the issue.
CODE FOR ACTIVITY A:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
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.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 categorias_list extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://XXXX/android_categoriaslist.php";
// JSON Node names
private static final String TAG_NAME = "nombreCategoria";
private static final String TAG_ID = "idCategoria";
private static final String TAG_CATEGORIAS = "Categorias";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categorias);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
//Starting single contact activity
Intent in = new Intent(getApplicationContext(),
ofertas_list.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_ID, cost);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(categorias_list.this);
pDialog.setMessage("Cargando datos...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CATEGORIAS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
// Phone node is JSON Object
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
categorias_list.this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_ID}, new int[] { R.id.name,
R.id.email });
setListAdapter(adapter);
}
}
}
CODE FOR SERVICE HANDLER:
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
You have to need maintain arraylist globalaly use
Adapter.notifyDatasetChanged(); for updating the list:
List view can be updated by updating your array adapt
YourArrayAdapterName.notifyDataSetChanged;
Above code must be added in your Activities onResume Method, Which is your firt activity for the List
Example:
#Override
protected void onResume() {
super.onResume();
yourAdapterName.notifyDataSetChanged();
// do other stuffs here.
}

Categories

Resources