I want to pass some argument get from intent to doBackground - android

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.

Related

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

JSON data not shown on second time an activity is opened

I have an activity that retreives objects from JSON.
The first time the activity is shown, all works fine.
But if the user goes forward and back and opens it again, then any data is shown.
This is my code:
package com.solinpromex.casajuventudtrescantos;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
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.util.Log;
import android.widget.ListView;
public class DondeEsta_T1_MainActivity extends Activity {
// Declare Variables
private static final String TAG_NAME = "nombreCategoria";
private static final String TAG_ID = "idPrueba";
private String name = "Categoria";
private String id = "id";
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
DondeEsta_T1_ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String ID_DES= "id_des";
static String TITULO_DES = "titulo_des";
static String CATEGORIAS_DES = "categoria_des";
static String LUGAR_DES = "lugar_des";
static String LATITUD_DES = "latitud_des";
static String LONGITUD_DES = "longitud_des";
static String IMAGEN_DES = "imagen_des";
static String DESCRIPCION_DES = "descripcion_des";
static String WEB_DES = "web_des";
static String MAIL_DES = "mail_des";
static String TEL_DES = "tel_des";
static String LUGAR_CORTO = "lugar_corto";
static String idPrueba = "idPrueba";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("MVASCO", "context is null!");
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
name = in.getStringExtra(TAG_NAME);
id = in.getStringExtra(TAG_ID);
idPrueba =in.getStringExtra(idPrueba);
setContentView(R.layout.dondeesta_t1_listview_main);
// Execute DownloadJSON AsyncTask
//new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
// Log.v("categoria para pasar a la URL", id_categoria_donde_esta);
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://.hidden url.../app_php_files/recuperar_categorias_donde_esta_t1.php?cat="+idPrueba);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("Categorias");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("id_des", jsonobject.getString("id_des"));
map.put("titulo_des", jsonobject.getString("titulo_des"));
map.put("categoria_des", jsonobject.getString("categoria_des"));
map.put("lugar_des", jsonobject.getString("lugar_des"));
map.put("latitud_des", jsonobject.getString("latitud_des"));
map.put("longitud_des", jsonobject.getString("longitud_des"));
map.put("descripcion_des", jsonobject.getString("descripcion_des"));
map.put("web_des", jsonobject.getString("web_des"));
map.put("mail_des", jsonobject.getString("mail_des"));
map.put("imagen_des", "http://www.solinpromex.com/casajuventud/sitios/"+jsonobject.getString("imagen_des"));
map.put("tel_des", jsonobject.getString("tel_des"));
map.put("lugar_corto", jsonobject.getString("lugar_corto"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new DondeEsta_T1_ListViewAdapter(DondeEsta_T1_MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
new DownloadJSON().execute();
}
}
What am I doing wrong?
put this
Intent in = getIntent();
// Get JSON values from previous intent
name = in.getStringExtra(TAG_NAME);
id = in.getStringExtra(TAG_ID);
idPrueba =in.getStringExtra(idPrueba);
into the Method onResume then it should work i think
Take also a look in this overview of the Lifecycle of an Activity
http://www.android-app-market.com/wp-content/uploads/2012/03/Android-Activity-Lifecycle.png

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

List view activity showing objects only the first time it is opened

In my Android app I have a list view activity showing MySQL objects downloaded from a web server via JSON.
I have detected following issue: the first time the activity is shown, the JSON objects are shown fine, but if the user goes back to the previous activity and then opens the list view activity again, any object is shown on the list and no error is thrown.
I need your help to solve this issue. Here is the activity 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://xxxxxxxx/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 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);
}
}
}
UPDATED 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://xxxxxxx/android_ofertaslist.php?id=";
// URL to get contacts JSON
// private static String url = "http://mujercanariasigloxxi.appgestion.eu/app_php_files/android_ofertaslist.php";
// 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";
#Override
public void onResume(){
super.onResume();
new GetContacts().execute();
}
// 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);
// 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);
}
}
}
You should probably perform the "new GetContacts().execute();" call in onResume(). See the Android documentation to get more familiar with the Android Activity lifecyle.
onCreate() is only called when the Activity is created. In your testing, the Activity is probably usually still alive, so onCreate() will not always be called when re-entering the Activity.
Put your new GetContacts().execute() in onResume() method.
onCreate() is called when you start Activity for the first time. If you leave activity, without killing it, and come back, your app goes thru onStart() ->onResume()`
Put onResume right before onCreate and remove new GetContacts().execute(); from onCreate().
...
// 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);
...

My aSyncTask is not working

my asynctask is not working. The dialog wont dismiss and the list is not being updated (i think because onPostExecute is not being called).I googled it, but without result.
package com.example.whs;
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.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class Albums extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// Array for the list
ArrayList<HashMap<String, String>> itemList;
// url to get the items
private static String url_all_products = "<my url here>";
// JSON variables
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_ITEMS = "items";
private static final String TAG_NAME = "name";
private static final String TAG_ID = "id";
private static final String TAG_USERNAME = "username";
//JSON array
JSONArray items = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_albums);
// HashMap for the items
itemList = new ArrayList<HashMap<String, String>>();
// Loading the items on the background
new LoadAllItems().execute();
// Get list-view
ListView lv = getListView();
// On item click
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
//do
}
});
}
// class for loading all items
class LoadAllItems extends AsyncTask<String, String, String> {
// Before
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(Albums.this);
pDialog.setMessage("Albums laden...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
// Get the products
#Override
protected String doInBackground(String... params) {
// Build Parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
//Get the JSON string
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params1);
// Check for response
Log.d("All Items: ", json.toString());
try {
// check for success tag
int success = json.getInt(TAG_SUCCESS);
if(success == 1) {
// found the items
items = json.getJSONArray(TAG_ITEMS);
// loop through the items
for (int i = 0; items.length() > i; i++){
// Get the item in variable c
JSONObject c = items.getJSONObject(i);
// Store in a variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String username = c.getString(TAG_USERNAME);
if(username == ""){
username = "onbekend";
}
// Create the HashMap
HashMap<String, String> map = new HashMap<String, String>();
// add it
map.put(TAG_ID, id);
map.put(TAG_USERNAME, username);
map.put(TAG_NAME, name);
// to arraylist
itemList.add(map);
}
}else{
// nothing found
Intent i = new Intent(getApplicationContext(), Index.class);
// close the previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e){
e.printStackTrace();
}
return null;
}
}
protected void onPostExecute(String result){
// dismiss dialog
pDialog.dismiss();
runOnUiThread(new Runnable(){
public void run(){
// Add adapter to the list
MenuAdapter adapter = new MenuAdapter(Albums.this, itemList);
ListView list = (ListView)findViewById(R.id.list);
list.setAdapter(adapter);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.albums, menu);
return true;
}
}
the loop is working correctly.
How to fix this?
1) you are trying to start an activity within the background thread, don't do this.
2) you are probably getting a json exception, just log more things so you can see what is happening
these may be why it never reaches onPostExecute
you can not perform UI related action in doInBackGround(), like you are strating a new activity in doInBaclground,
Intent i = new Intent(getApplicationContext(), Index.class);
// close the previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);

Categories

Resources