Android progressdialog thread exception - android

My app uses the CallLog to collect data and put it into a listview. As this takes time, I tried to use progressdialog to show the user the status of the loading. Unfortunately (I have used progressdialog before) eclipse throws me an error: ERROR/AndroidRuntime(771): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
public class Calls extends Activity {
//declaring variables
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calls);
lv1 = (ListView) findViewById(R.id.ListView01);
pd = new ProgressDialog(Calls.this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("Loading contacts");
pd.show();
//Thread thread = new Thread() {
//public void run() {
Calls.this.runOnUiThread(new Runnable() {
#Override
public void run() {
//collecting data from CallLog, putting data into an array
//Here comes the hard part, which is the root of the problem:
final ArrayList<SearchResults> results = new ArrayList<SearchResults>();
SearchResults sr1 = new SearchResults();
for (int b=0; b<storage.length; b++)
{
for (int e=0; e<storage[b].length; e++)
{
if (e+3 < storage[b].length)
{
arr_split_all.add(storage[b][e] + " " + storage[b][e+1] + " " + storage[b][e+2] + " " + storage[b][e+3]);
sr1 = new SearchResults();
sr1.setData1(storage[b][e+2]);
sr1.setData2(storage[b][e]);
sr1.setData3(storage[b][e+1]);
sr1.setData4(storage[b][e+3]);
sr1.setBitmap2(bitmaparray[b]); //bitmaparray has the same size as storage, and there is no problem with this
results.add(sr1);
}
}
}
lv1.setAdapter(new MyCustomBaseAdapter(Calls.this, results)); //problematic row
handler.sendEmptyMessage(0);
}
};
thread.start();
}
}//end of onCreate
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
pd.dismiss();
}
}); //ADDED a )
}//end of class
// SearchResults is another class:
public class SearchResults extends Application{
private String data1 = "";
private String data2 = "";
private String data3 = "";
private String data4 = "";
private String bitmap = "";
private Bitmap bitmap2;
public void setData1(String data1) {
this.data1 = data1;
}
public String getData1() {
return data1;
}
//etc...
}
And I am using a BaseAdapter class to put the data into the appropriate places of the listview (which consists of an imageview and four textviews), but I don't think that is relevant now.
According to Logcat, the problem is with the lv1.setAdapter(new MyCustomBaseAdapter(Calls.this, results)); row. If I attach an arraylist to the listview, it is working fine. Without the progressdialog all textviews and the imageview of each row of the listview is loaded properly.

The problem is your findViewById() call to your ListView01 (and later on, the setAdapter() call). You cannot modify (or access) views from a custom thread. This has to be done on the UI thread, either via runOnUiThread() or in a place where the UI thread runs.

Related

how to extract integer value on textview to another integer inside listview onclicklistener

I working on an Android project which has a ListView and contains one TextView to display the contact and contact are stored in my website in form of json.
json link for contacts
I am able to parse the contacts I have no problem with that. But the problem is the parsed data is displayed as a number like "776057619" in the TextView and I want this TextView number to be taken and stored in a separate variable. By doing this I can use it to prompt the user "weather you want to call that particular number"??. But I don't no how to pull that number from the TextView to a separate variable and use to call inside ListView's OnItemClickListener
below is my code
public class Contactmedia extends ListActivity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String READ_CONTACT_URL = "http://www.iamnotcrazy.hol.es/webservice/contact.php";
private static final String TAG_NUMBER ="number";
private static final String TAG_POSTS = "posts";
private JSONArray mid = null;
//manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mContactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactmedialist);
}
#Override
protected void onResume() {
super.onResume();
new LoadComments().execute();
}
/**
* Retrieves json data of comments
*/
public void updateJSONdata() {
mContactList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_CONTACT_URL);
try {
mid= json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mid.length(); i++) {
JSONObject c = mid.getJSONObject(i);
String number = c.getString(TAG_NUMBER);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NUMBER, number);
mContactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into our listview
*/
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mContactList,
R.layout.contactmediadesign, new String[] { TAG_NUMBER
}, new int[] { R.id.contactno
});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
/* this is where i have problem how to get that number without converting to string*/
TextView v = (TextView)view.findViewById(R.id.contactno);
int myNum = Integer.parseInt(v.getText().toString());
/* and here i want use that mynum after getiing phonenumber for calling purpouse ass shown below
* but its not working :(*/
if (position == 0){
Toast.makeText(getApplicationContext(), "yes you done it!!", Toast.LENGTH_SHORT).show();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+"myNum"));
startActivity(callIntent);
}
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Contactmedia.this);
pDialog.setMessage("Loading complaints...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
Since you actually need string, you don't have to convert to integer at all:
TextView v = (TextView)view.findViewById(R.id.contactno);
...
callIntent.setData(Uri.parse("tel:"+ v.getText().toString()));
or if you do need to store that number in variable for some reason, you should use String instead
TextView v = (TextView)view.findViewById(R.id.contactno);
string myNum = v.getText().toString();
...
callIntent.setData(Uri.parse("tel:" + myNum));
I would recommend getting the data associated with that position rather than trying to parse the view to get it.
You can get the data from the adapter with adapter.getItem(int pos). Just make adapter final or a member variable to access it in the OnItemClickListener.
First of all you should check your Manifest file, you should have this outside the "application" tag but within the "manifest" tag:
<uses-permission android:name="android.permission.CALL_PHONE" />
Try to do something like this in your code:
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + v.getText().toString()));
startActivity(callIntent);
You should use String value instead of int
remove the double quotation on mynum. you can also use basic oop to save your integer value. fyi, myNum doesnt have to be an integer. it can be a string
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
/* this is where i have problem how to get that number without converting to string*/
TextView v = (TextView)view.findViewById(R.id.contactno);
int myNum = Integer.parseInt(v.getText().toString());
setNumber(myNum); //saving the myNum variable
System.out.println("number is: " + getNumber());//if you want to get the value of myNum, just call the getNumber()
if (position == 0){
Toast.makeText(getApplicationContext(), "yes you done it!!", Toast.LENGTH_SHORT).show();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+ myNum));//remove the quotation for myNum
startActivity(callIntent);
}
}
private int number;
void setNumber(int number){
this.number=number;
}
int getNumber(){
return number;
}

How to use listview from different xml layout file

I am working on android ListView and i am getting one issue.I created one list view into the XML file installation.xml and i want to use that list view into my Searchdata.java. so basically what i want that when i click on searchdata button than data is fetched from web service and after parsing, it will saved into the listview.and when i click on Installation View button than new window will be appear where i could see that list data.
SearchData.java
public class SearchData extends Activity {
EditText Keyword;
JSONParser jsonparser = new JSONParser();
ListView Datalist;
HorizontalScrollView VideoDatalist;
ArrayList<HashMap<String, String>> DataList;
ArrayList<HashMap<String, String>> VideoDataList;
JSONArray contacts = null;
private ProgressDialog pDialog;
ImageButton searchdata,InstallationView;
String Keyvalue = new String();
private static final String TAG_InnerText = "InnerText";
private static final String TAG_Title = "Title";
private static final String TAG_URL = "URL";
private static final String TAG_VIDEO_URL = "URL";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_data);
InstallationView=(ImageButton)findViewById(R.id.InstallationView);
Keyword = (EditText) findViewById(R.id.KeyData);
Datalist=(ListView)findViewById(R.layout.activity_installation);
VideoDatalist=(HorizontalScrollView)findViewById(R.id.Horizontallist);
searchdata=(ImageButton)findViewById(R.id.searchicon);
String Keyvalue = new String();
DataList = new ArrayList<HashMap<String, String>>();
VideoDataList = new ArrayList<HashMap<String, String>>();
searchdata.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new ReadData().execute();
}
});
InstallationView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
startActivity(new Intent(SearchData.this, Installation.class));
}
});
}
public class ReadData extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchData.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(Void... arg0) {
try{
Keyvalue=Keyword.getText().toString();
String Jsonstr = jsonparser.makeHttpRequest("http://10.47.93.26:8080/Search/api/Search/"+Keyvalue);
try {
if (Jsonstr != null) {
JSONArray jsonObj = new JSONArray (Jsonstr);
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String name = c.optString(TAG_Title);
String url = c.optString(TAG_URL);
HashMap<String, String> info = new HashMap<String, String>();
if( !name.isEmpty() )
{
info.put(TAG_Title, name);
}
else
{
info.put(TAG_Title,"User Manual");
}
if(url.contains("youtube"))
{
info.put(TAG_URL, url);
VideoDataList.add(info);
}
else
{
info.put(TAG_URL, url);
DataList.add(info);
}
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
SimpleAdapter adapter = new SimpleAdapter(
SearchData.this, DataList,
R.layout.list_item, new String[]
{
TAG_Title
}, new int[] {
R.id.InnerText });
Datalist.setAdapter(adapter);
}
}
}
web service running and parsing code is running correctly. i am getting error at post method,so can you help me on this.
Error
Call your Installation activity in onClick() method:
And pass your ArrayList data through intent,
InstallationView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
Intent intent= new Intent(SearchData.this, Installation.class);
intent.putParcelableArrayListExtra("HASH_MAP",DataList);
startActivity(intent);
}
});
In your Installation activity class,set the view in onCreate() and initialize listview from xml file:
setContentView(R.layout.activity_installation);
ListView listView = (ListView)findViwById(R.id.listview);
And try to get the data from intent:
ArrayList<HashMap<String,String>> hashmap_dataList = getIntent.getParcelableArrayListExtra("HASH_MAP");
then do whatever you want with listview and hashmap.
In the onCreate(...) method of your SearchData Activity, the following can never work and will always return 'null' (hence your NullPointerException)...
Datalist=(ListView)findViewById(R.layout.activity_installation);
Calling findViewById(...) will only work for any UI elements which have been inflated when you called setContentView(...). In this case you used R.layout.activity_search_data for your layout file which doesn't contain a ListView with an id of R.layout.activity_installation which is, by the way, a resource id of a layout file and not a resource id of a UI element.
The only way you can do what you need is to put your data as an extra into the Intent you use when you call...
startActivity(new Intent(SearchData.this, Installation.class));
...when the Installation Activity is created it will then need to get the data and create its own adapter.
EDIT: HashMap is Serializable and can be passed as an Intent extra. Pass your DataList HashMap as follows...
Intent i = new Intent(SearchData.this, Installation.class);
i.putExtra("data_list", DataList);
startActivity(i);
In the Installation Activity you can then use...
getIntent().getSerializableExtra("data_list");

"Can't create handler inside thread that has not called Looper.prepare()" in AsyncTask

I got a weird problem with an android activity : I re-used one of my previous activity that works well, but this time all I got is "Can't create handler inside thread that has not called Looper.prepare()"
I tried to debug, and everything in the async task is performing well but when I reach then end of onPostExecute() the error is raised.
So I tried to disable my process about the process dialog, the only change is that it's crashing on line upper.
Here is the code :
public class DateActivity extends ActionBarActivity{
ProgressDialog mProgressDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date);
ActionBar actionBar = this.getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(getResources().getString(R.string.actionbar_titre_date));
if (VerifConnexion.isOnline(this)) {
this.mProgressDialog = ProgressDialog.show(this, getResources().getString(R.string.loading),
getResources().getString(R.string.loading), true);
new QueryForDateTask().execute(this.mProgressDialog, this, this.getApplicationContext());
} else {
...
}
});
alertDialog.show();
}
}
private class QueryForDateTask extends
AsyncTask<Object, Void, ArrayList<String>> {
private ProgressDialog mProgressDialog;
private Activity act;
private Context context;
protected ArrayList<String> doInBackground(Object... o) {
this.mProgressDialog = (ProgressDialog) o[0];
this.act = (Activity) o[1];
this.context = (Context) o[2];
ArrayList<String> listeDate = this.parseJSON(this.startQuerying());
return listeDate;
}
public JSONObject startQuerying() {
JSONRequest jr = new JSONRequest();
String from = getResources().getString(R.string.api_param_from);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.FRANCE);
from += "=" + sdf.format(new Date());
String url = getResources().getString(
R.string.api_dates_json);
JSONObject jo = jr.getJSONFromUrl(url + "?" + from);
return jo;
}
public ArrayList<String> parseJSON(JSONObject jsonObject) {
ArrayList<String> l = new ArrayList<String>();
try {
JSONArray array = jsonObject.getJSONArray("dates");
if (array != null) {
for (int i = 0; i < array.length(); i++) {
String type = array.getString(i);
l.add(type);
} // fin parcours JSONArray
}
} catch (Exception _e) {
}
return l;
}
protected void onProgressUpdate(Integer... progress) {
// setProgressPercent(progress[0]);
}
protected void onPostExecute(ArrayList<String> lDate) {
// Create items for the ListView
DateAdapter adapter = new DateAdapter(this.context, R.layout.searchitem_date, lDate, this.act);
// specify the list adaptor
((ListView)findViewById(R.id.list)).setAdapter(adapter);
this.mProgressDialog.dismiss();
}
} // fin async
}
I tried this to replace the call to the AsyncTask :
runOnUiThread(new Runnable() {
public void run() {
QueryForDateTask task = new QueryForDateTask();
task.execute(DateActivity.this.mProgressDialog, DateActivity.this, DateActivity.this.getApplicationContext());
}
});
(like explained in Asynctask causes exception 'Can't create handler inside thread that has not called Looper.prepare()' as far as I understood), but the result is exactly the same.
So I can't understand why it is not working in this activity despite all is ok for the other ones of the project.
Any clue ?
Thank a lot for all ideas :)
Just a post to mark the trouble as resolved :
the adapter i used was buggy in parsing parameters and throwed a NullPointerException.
I just fixed it, the AsyncTask is now running without problem.

thread exiting error in android

Please help with this error .... In the following code the get info function works correctly but it gives an error saying the thread caught an exception at exiting.... I am trying to use a tab host and the first tab page is the following... In this i show a progress dialog until i get my data and then show it in a list view
public class History extends Activity implements OnItemClickListener
{
/** Called when the activity is first created. */
ListView list;
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems;
//DEFINING STRING ADAPTER WHICH WILL HANDLE DATA OF LISTVIEW
ArrayAdapter<String> adapter;
private String resDriver,resPassenger,ID;
private ProgressDialog dialog;
ArrayList<HashMap<String, Object>> listInfo = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> item;
JSONObject jDriver;
//JSONObject jPassenger;
// Make strings for logging
private final String TAG = this.getClass().getSimpleName();
private final String RESTORE = ", can restore state";
private final String state = "Home Screen taking care of all the tabs";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent loginIntent = getIntent();
ID = loginIntent.getStringExtra("ID");
listItems = new ArrayList<String>();
Log.i(TAG, "Started view active rides");
setContentView(R.layout.searchresults);
list = (ListView)findViewById(R.id.ListView01);
list.setOnItemClickListener(this);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listItems);
list.setAdapter(adapter);
getInfo();
}
The function getInfo is used to start a thread which shows a dialog box and starts a http request to get some data ...
public void getInfo(){
GetInfoThread checkUpdate = new GetInfoThread();
checkUpdate.start();
dialog = ProgressDialog.show(History.this, "Retrieving Info","Please Wait ...", true);
}
private class GetInfoThread extends Thread
{
public void run() {
jDriver = new JSONObject();
try {
jDriver.put("ID", ID);
jDriver.put("task", "GET DATES");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
listItems = new ArrayList<String>();
Log.i(TAG,"Sending data for the driver rides");
resDriver = HTTPPoster.sendJson(jDriver,"http://dsadsada"); // Any Server URL
JSONObject driver;
try {
driver = new JSONObject(resDriver);
Log.i(TAG,"Recieved Driver details");
listItems.add(array[0]);
handler.sendEmptyMessage(0);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
listItems.add("No driver rides created");
handler.sendEmptyMessage(0);
}
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
dialog.dismiss();
Log.i(TAG,"hello 123");
adapter.notifyDataSetChanged();
}
};
}
I am not sure exactly what is causing your error but I suspect it has to do with UI changes not running on the actual UI thread. In Android there is a class called AsyncTask that will do the threading for you and handle the passing of data between the background thread an the UI thread. I would suggest rewriting your code to utilize the AsyncTask class.

Handler will not bind to main thread

So my code seems to run just fine until it hits this line
adapter.notifyDataSetChanged();
The error that pops up in the logcat is CalledFromWrongThreadException. The debug also shows the handler being run in the Background thread. How do I get the handler to bind to the main thread, and not the background one? I thought I just had to create the handler in the main thread, but I guess I am wrong, quite possible I am new to andriod. How do I fix this?
//Imports are included
public class DirectoryActivity extends ListActivity {
private ProgressDialog ProgressDialog = null;
private ArrayList<DirectoryListing> listing = null;
private DirectoryAdapter adapter;
private Runnable viewOrders;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.directory);
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (listing != null && listing.size() > 0) {
adapter.notifyDataSetChanged();
for (int i = 0; i < listing.size(); i++)
adapter.add(listing.get(i));
Log.e("log_tag", "\nStill running\n");
}
ProgressDialog.dismiss();
adapter.notifyDataSetChanged();
}
};
listing = new ArrayList<DirectoryListing>();
adapter = new DirectoryAdapter(this, R.layout.rows, listing);
setListAdapter(adapter);
ProgressDialog = ProgressDialog.show(DirectoryActivity.this, "Please wait...", "Retrieving data ...", true);
viewOrders = new Runnable() {
#Override
public void run() {
listing = PreparePage.getArrayList();
handler.handleMessage(null);
}
};
Thread thread = new Thread(null, viewOrders, "Background");
thread.start();
}
private static class PreparePage {
protected static ArrayList<DirectoryListing> getArrayList() {
ArrayList<DirectoryListing> listings = new ArrayList<DirectoryListing>();
JSONObject information = GetPageData.getJSONFromURL(url);
Iterator key = information.keys();
while (key.hasNext()) {
String id = (String) key.next();
JSONObject info = null;
try {
info = information.getJSONObject(id);
} catch (JSONException e) {
e.printStackTrace();
}
String name = "", title = "", photo = "";
try {
name = info.get("firstName") + " " + info.get("lastName");
title = info.getJSONObject("position").getString("name");
photo = info.optString("photoPath", "none");
} catch (JSONException e) {
e.printStackTrace();
}
listings.add(new DirectoryListing(name, title, photo));
}
return listings;
}
}
}
Try calling handler.sendEmptyMessage(0); instead of handler.handleMessage(null);
I don't know why this would cause the errors you are seeing, but this is how I have it set up when I use handler and thread instead of AsyncTask. And I have have never seen that error doing it this way.
#Nguyen is right though AsyncTask is the preferred way to handle these types of things now. And it actually makes it much easier to do.
AsyncTask docs
AsyncTask Example
In my experience, you should create your own class that extends AsyncTask class to do something at background. This is a simpler and more effectively than using thread + handler.

Categories

Resources