how to show toast in getDataTaskmethod? [duplicate] - android

This question already has an answer here:
how to fix getDataTask method error?
(1 answer)
Closed 9 years ago.
this is my code below which work perfectly only problem is not show toast mesage code is blast i want to display toast mesage if Status is 0 in this line if (status.equals("1"))
show toast message but code is blast if i comment Toast then code run perfectly help me what do i do??
public class thirdstep extends Activity {
ListView listCategory;
String status;
String message;
String MenuSelect;
ProgressBar prgLoading;
long Cat_ID;
String Cat_name;
String CategoryAPI;
int IOConnect = 0;
TextView txtAlert;
thirdstepAdapter cla;
static ArrayList<String> Category_ID = new ArrayList<String>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
ImageButton btnback = (ImageButton) findViewById(R.id.btnback);
listCategory = (ListView) findViewById(R.id.listCategory2);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
cla = new thirdstepAdapter(thirdstep.this);
new getDataTask().execute();
listCategory.setAdapter(cla);
btnback.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
Intent iGet = getIntent();
Cat_ID = iGet.getLongExtra("category_id", 0);
Cat_name = iGet.getStringExtra("category_name");
Toast.makeText(this, Cat_ID + Cat_name, Toast.LENGTH_SHORT).show();
MenuSelect = Utils.MenuSelect;
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(thirdstep.this,
fourthscreen.class);
iMenuList.putExtra("Cat_ID",Cat_ID);
iMenuList.putExtra("Menuitem", Category_ID.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void>{
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
if((Category_ID.size() > 0) || IOConnect == 0){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}
public void parseJSONData() {
CategoryAPI = Utils.MenuList + Cat_ID;
clearData();
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json = new JSONObject(str);
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
message = json2.getString("message");
if (status.equals("1")) {
JSONObject data = json.getJSONObject("data");
JSONArray school = data.getJSONArray("menu_groups");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
Category_ID.add(object.getString("id"));
Category_name.add(object.getString("title"));
Category_image.add(object.getString("image"));
}
}
else
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Your toast message is within the parseJsonData method which is called from the doInBackground method of your asynctask.
You can not update the user interface thread from a background thread.
You have two options here
1) You can publish the progress publishProgress(1) of the thread passing in an integer value to be used as a flag which you can pick up on in the onPublishProgress listener and show your toast there
or
2) As your method has finished by this point then make the parseJsonData set an integer variable global to the asynctask and in the onPostExecute method pass something back to the listener to indicate that a toast needs to be shown
Update based on comments
Replace
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
with
{
publishProgress(1);
}
Add the missing onProgressUpdate() method to your asynctask
#Override
protected void onProgressUpdate(Integer... percent) {
//Call your listeners.onProgressUpdate(percent) here and show the
//Or
super.onProgressUpdate(percent);
if (percent[0] == 1){
Toast.makeText(thirdstep.this, message, Toast.LENGTH_SHORT).show();
}
}
I'm not here to write your code for you. Do some research on how to properly write an async task and publish progress
Here is a good starting point
http://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/
You should be aware of orientation changes and how that will effect your asynctask (I avoid the pitfals of this by using a fragment
This is the design pattern I use for async tasks
http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html
But for handling web services, be nice to your users and let the android system work out when to download data etc and don't drain their battery and use a sync adapter with an intentservice instead of an asynctask. There are already too many crappy apps out there that take the asynctask approach for consuming web services. Please don't add yours to the list
Do it this way
http://developer.android.com/training/sync-adapters/creating-sync-adapter.html
It's a lot of extra learning curve but your a programmer right? You should be giving your users the best possible experience.
BTW You are getting down votes because you are demanding code to be written for you. I'm hoping this is just a language barrier and not an attitude problem.

Surround your Toast with this
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), message, Toast.LENGTH_SHORT).show();
}
});

Related

On scroll listener calling asynctask twice thrice or some times more on scrolling once on listview

As i am loading data from web through an api as user scrolls to bottom in listview but When i scroll on listview for once it calls asynctask for many times in my activity which causes duplicate data in listview and in case of exception lots of dialog and toast on activity and when i scrolled to bottom and simply just touch my listview on scroll method get fires which calls asynctask again for many time so please tel me how to prevent this.
here is my code of onscroll method.
listView.setOnScrollListener(new OnScrollListener() {
// boolean mIsScrollingUp;
// int mLastFirstVisibleItem;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
if(scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL)
userscrolled=true;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
int lasinscren = firstVisibleItem + visibleItemCount;
if(userscrolled&&(lasinscren==totalItemCount)&&!lodinmore&&(visibleItemCount<totalItemCount)&&havedata)
{
progress = true;
if(Search_API==false){
if(connectionDetector.isConnectintoInternet()){
System.out.println("inside listview on scroll function");
darList_task = new DAR_list_task(DAR_Activity.this).execute();
lodinmore = true;
}else
{
Toast.makeText(getApplicationContext(), "No internet connection", Toast.LENGTH_SHORT).show();
}
}else
{
new search_task(DAR_Activity.this).execute();
}
}
}
});
here's my asynctask
public class DAR_list_task extends AsyncTask<Void, Void, Void>
{
Context activity;
public DAR_list_task(Context activity) {
// TODO Auto-generated constructor stub
this.activity = activity;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if(progress==true){
if(limit==0)
{
dialog = new Dialog(DAR_Activity.this);
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
LinearLayout linearLayout = (LinearLayout)getLayoutInflater().inflate(R.layout.dialog_progress, null);
dialog.setContentView(linearLayout);
ProgressBar progressBar1 = (ProgressBar)findViewById(R.id.progress_dialog);
dialog.setCancelable(false);
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
dialog.getWindow().setGravity(Gravity.CENTER);
}else
{
progressBar.setVisibility(View.VISIBLE);
}
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
response=null;
lodinmore = true;
URL Url;
try {
byte[] data;
data = login_id.getBytes("UTF-8");
String login_base_64 = Base64.encode(data);
data = gcm_id.getBytes("UTF-8");
String gcm_base64= Base64.encode(data);
if(url.contentEquals(""))
{
Url = new URL(getResources().getString(R.string.dar_list_view));
}else
{
Url = new URL("http://"+url+"/smart_oms/dar_app/view_dar.php");
}
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("login_id", login_base_64));
nameValuePairs.add(new BasicNameValuePair("gcm_id", gcm_base64));
nameValuePairs.add(new BasicNameValuePair("limit", String.valueOf(limit)));
HttpURLConnection httpURLConnection = (HttpURLConnection)Url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setUseCaches(false);
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
bufferedWriter.write(getQueryString(nameValuePairs));
bufferedWriter.flush();
bufferedWriter.close();
os.close();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
response = BufferReaderMaker.readContentFromIS(inputStream);
}catch( final UnknownHostException ex)
{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}catch (final ConnectTimeoutException e) {
// TODO: handle exception
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
catch (Exception e) {
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Object json = null;
try {
if(response!=null)
{
if(progress==false)
{
dar_List_Items.clear();
dar_Aadapter = new DAR_Aadapter(DAR_Activity.this, dar_List_Items);
listView.setAdapter(dar_Aadapter);
dar_Aadapter.notifyDataSetChanged();
}
try {
json = new JSONTokener(response).nextValue();
} catch (JSONException e1) {
// TODO Auto-generated catch block
ErrorDialog errorDialog = new ErrorDialog();
errorDialog.Dialog(activity, statusCode, response, login_id, "", new DAR_list_task(activity));
}
if(json instanceof JSONArray)
{
havedata=false;
Toast.makeText(getApplicationContext(), "No More DAR", 0).show();
}else if(json instanceof JSONObject)
{
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("view_dar_detail");
for(int i =0 ;i<jsonArray.length();)
{
JSONObject json_data = jsonArray.getJSONObject(i);
String dar_id = json_data.optString("customer_id");
String Customer_name = json_data.optString("customer_name");
String Contacted= json_data.optString("contact_person_name");
String product = json_data.optString("product");
String status = json_data.optString("dar_status");
String Contact_type = json_data.optString("contact_type");
String created_date = json_data.optString("dar_created_date");
String request_date = json_data.optString("requeste_date");
DAR_List_Item dar_List_Item = new DAR_List_Item(dar_id,Customer_name, Contacted, Contact_type, product, status, created_date, request_date,"abcd");
dar_List_Items.add(dar_List_Item);
i++;
}
int index = listView.getFirstVisiblePosition();
View v= listView.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
listView.setAdapter(null);
DAR_Aadapter aadapter = new DAR_Aadapter(DAR_Activity.this, dar_List_Items);
listView.setAdapter(aadapter);
aadapter.notifyDataSetChanged();
listView.setSelectionFromTop(index, top);
}else
{
ErrorDialog errorDialog = new ErrorDialog();
errorDialog.Dialog(activity, statusCode, response, login_id, "", new DAR_list_task(activity));
}
lodinmore = false;
}
lodinmore = false;
} catch (JSONException e) {
// TODO Auto-generated catch block
ErrorDialog errorDialog = new ErrorDialog();
errorDialog.Dialog(activity, statusCode, response, login_id, "", new DAR_list_task(activity));
}
if(progress==true){
if(limit==0)
{
dialog.dismiss();
}else{
progressBar.setVisibility(View.GONE);
}
}
if(json instanceof JSONObject)
limit = limit +10;
}
}
pLease help me in this i have tried a lot of things like using flag value and many more but non of them working for me.
How to prevent calling asynctask calling many time?
how to prevent asynctask to fired when i scrolled to bottom and just touch the list?
There is a work around for this:
final int lastItem = firstVisibleItem + visibleItemCount;
if(lastItem == totalItemCount) {
if(lastLastitem !=lastItem){ //to avoid multiple calls for last item, declare it as a field in your Activity
lastLastitem = lastItem;
// Your async task here
}
An easy way is define a boolean param:
if(view.getLastVisiblePosition() == totalItemCount-1 && isLoadMore){
isLoadMore = false;
pageNum++;
loadMoreData(searchStr, donViID, pageNum, Constant.RECORD_PER_PAGE);
}

Socket Programming with Broadcast Recevier

I am developing Android application(online marketing), within this project i am using socket programming for communication with server, when i communicate with server if server does not give me any response within 30 sec then my asynctask will close automatically, but now problem is i want to save server response in sqlite on receiving response from server please provide me the necessary help thank
you in advance.
Here is My Asyntask :
public class SendToserver extends AsyncTask<Integer, Integer, Integer>
{
int iReturn;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog(Registartion.this, "Please Wait...");
super.onPreExecute();
}
#Override
protected Integer doInBackground(Integer... params) {
// TODO Auto-generated method stub
ServerData = runm(IMEINo);
if (ServerData.equalsIgnoreCase("IsNull"))
{
iReturn = 2;
}
else {
iReturn = 1;
}
return iReturn;
}
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
if (iReturn == 1)
{
String ServerIP = edtServerIpAddress.getText().toString();
String ServerPort = edtServerPort.getText().toString();
registartionModel = new RegistartionModel();
registartionModel.setServerIPAdreess(ServerIP);
registartionModel.setPort(ServerPort);
registrationDb = new RegistrationDb(getApplicationContext());
registrationDb.open();
registrationDb.insertData(registartionModel);
registrationDb.close();
Intent i = new Intent(getBaseContext(), LoginActivity.class);
startActivity(i);
Registartion.this.finish();
System.gc();
}
else if (iReturn == 2)
{
showDialogBox("Please Input Correct Server IP and Port");
}
super.onPostExecute(result);
}
}
My Server Communication Method(runm):
#SuppressLint("NewApi")
public String runm(String DId)
{
try {
socket = new Socket(SERVER_IP, SERVERPORT);
out = new PrintStream(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.write((DId + "|" +"REG").getBytes());
ServerData = in.readLine();
System.err.println("Server Data in Runm :- " + ServerData);
if(ServerData == null || ServerData.equalsIgnoreCase(""))
{
ServerData="IsNull";
}
}
catch (NetworkOnMainThreadException e)
{
ServerData = "IsNull";
}catch (IOException ex) {
ServerData = "IsNull";
}
return ServerData;
}
Should i use Broadcast Receiver ?

Start timer after button click

I want to start timer after clicking on Button and poll for every 3 secs.
I am using following code.
private EditText url;
private Button submit;
private TextView error;
String some_URL;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live);
loadviews();
handler=new Handler();
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
some_URL="http://"+url.getText().toString();
getStatus();
}
}
});
private void getStatus() {
// TODO Auto-generated method stub
handler.postDelayed(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
new Class_Poll().execute(some_URL);
error.setText("ID:"+ID+"\n"+
"Name:"+name+"\n" +
"Type:"+type+"\n"+
"Status:"+Status+"\n"+
"Content:"+Content);
}
}, 3000);
}
}
private void loadviews() {
// TODO Auto-generated method stub
url=(EditText)findViewById(R.id.url);
submit=(Button)findViewById(R.id.Submit);
error=(TextView)findViewById(R.id.log);
error.setMovementMethod(new ScrollingMovementMethod());
}
private class Class_Poll extends AsyncTask<String, Void, Void>{
private final HttpClient Client = new DefaultHttpClient();
#Override
protected Void doInBackground(String... arg0) {
// TODO Auto-generated method stub
Content=executeHttpRequest(some_URL);
return null;
}
#Override
protected void onPostExecute(Void unused) {
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(Content);
ID=jsonResponse.optString("ID").toString();
name=jsonResponse.optString("Name").toString();
type=jsonResponse.optString("Type").toString();
Status=jsonResponse.optString("Status").toString();
error.setText("ID:"+ID+"\n"+
"Name:"+name+"\n" +
"Type:"+type+"\n"+
"Status:"+Status+"\n"+
"Content:"+Content);
} catch (JSONException e) {
error.setText(e.toString());
}
//Toast.makeText(getApplicationContext(), "ID:"+ID+" Name:"+name+" Type:"+type+" Status:"+Status, Toast.LENGTH_LONG).show();
}
}
public static String executeHttpRequest(String url)
{
HttpURLConnection urlConnection = null;
try
{
URL httpUrl = new URL(url);
urlConnection = (HttpURLConnection) httpUrl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.addRequestProperty("Accept", "text/html,text/xhtml,application/xhtml+xml,application/xml;");
urlConnection.setConnectTimeout(10000);
InputStream in = null;
try
{
in = urlConnection.getInputStream();
} catch (NullPointerException e)
{
Log.e("Check", "Request Failed, Check the url");
return null;
}
if (in != null)
{
in = new BufferedInputStream(in);
String response = readStream(in);
Log.e("Check", response + "");
if (response != null && !response.isEmpty())
{
// statusTrace.print(TAG, "Operation executed : " +
// isSuccess(response));
return response;
}
else
{
Log.e("Check", "Request Failed");
}
} else
;//statusTrace.print(TAG, "Request Failed");
} catch (IOException e)
{
Log.e("Check", "Error : " + e.toString());
//statusTrace.print("Error", "Network Error. Check connection and Tuxedo IP");
}
return null;
}
public static String readStream(InputStream in)throws IOException {
// TODO Auto-generated method stub
InputStreamReader is = new InputStreamReader(in);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(is);
String read = br.readLine();
while (read != null)
{
sb.append(read);
read = br.readLine();
}
return sb.toString();
}
error is TextView in which I am displaying some Text.
And I am invoking web service in Asyntask. So it is not executing asynchtask for delay of 3 seconds after button click.
I don't know where know what is the problem exactly. It should execute actually, my textview is not getting updated for each 3 seconds.
Timer runs on a different thread you should not invoke AsyncTask from a background thread.
Please read Threading rules #
http://developer.android.com/reference/android/os/AsyncTask.html
public void scheduleAtFixedRate (TimerTask task, long delay, long period)
Added in API level 1
Schedule a task for repeated fixed-rate execution after a specific delay has passed.
Parameters
task the task to schedule.
delay amount of time in milliseconds before first execution.
period amount of time in milliseconds between subsequent executions.
Throws
IllegalArgumentException if delay < 0 or period <= 0.
IllegalStateException if the Timer has been canceled, or if the task has been scheduled or canceled.
Your delay is 0. See this }, 0, 3000);
can you suggest me an alternative to this so that I can execute
AsynchTask at after 3 secs of delay??
I assume you want to invoke asynctask after a 3 sec delay
You can use a Handler
Handler handler = new Handler():
handler.postDelayed(new Runnable(){
#Override
public void run() {
// run something after 3 sec delay
}
}, 3000);
Edit:
public class MainActivity extends Activity
{
private EditText url;
private Button submit;
private TextView error;
String Content;
String some_URL;
Handler handler;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live);
loadviews();
handler=new Handler();
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
some_URL="http://"+url.getText().toString();
getStatus();
}
});
}
private void getStatus() {
// TODO Auto-generated method stub
handler.postDelayed(new Runnable(){
#Override
public void run() {
new Class_Poll().execute(some_URL);
}
}, 3000);
}
private void loadviews() {
// TODO Auto-generated method stub
url=(EditText)findViewById(R.id.url);
submit=(Button)findViewById(R.id.Submit);
error=(TextView)findViewById(R.id.log);
error.setMovementMethod(new ScrollingMovementMethod());
}
private class Class_Poll extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... arg0) {
String _response;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(arg0[0]);
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
}catch(Exception e)
{
e.printStackTrace();
}
return _response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(result);
String ID=jsonResponse.optString("ID").toString();
String name=jsonResponse.optString("Name").toString();
String type=jsonResponse.optString("Type").toString();
String Status=jsonResponse.optString("Status").toString();
error.setText("ID:"+ID+"\n"+
"Name:"+name+"\n" +
"Type:"+type+"\n"+
"Status:"+Status+"\n"+
"Content:"+Content);
} catch (JSONException e) {
error.setText(e.toString());
}
}
}
}

how to fix getDataTask method error?

below is my code there is a problem some where in getDataTask if i remove this class is work fine and print Toast message Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); but what is problem in my getDataTask im parsing below json file problem is some where in doinbackground method help me please
{"status":0,"message":"No such school found"}
public class thirdstep extends Activity {
ListView listCategory;
String status;
String message;
String MenuSelect;
ProgressBar prgLoading;
long Cat_ID;
String Cat_name;
String CategoryAPI;
int IOConnect = 0;
TextView txtAlert;
thirdstepAdapter cla;
static ArrayList<String> Category_ID = new ArrayList<String>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
ImageButton btnback = (ImageButton) findViewById(R.id.btnback);
listCategory = (ListView) findViewById(R.id.listCategory2);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
cla = new thirdstepAdapter(thirdstep.this);
new getDataTask().execute();
listCategory.setAdapter(cla);
btnback.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
Intent iGet = getIntent();
Cat_ID = iGet.getLongExtra("category_id", 0);
Cat_name = iGet.getStringExtra("category_name");
Toast.makeText(this, Cat_ID + Cat_name, Toast.LENGTH_SHORT).show();
MenuSelect = Utils.MenuSelect;
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(thirdstep.this, fourthscreen.class);
iMenuList.putExtra("Cat_ID",Cat_ID);
iMenuList.putExtra("Menuitem", Category_ID.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void>{
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
if((Category_ID.size() > 0) || IOConnect == 0){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}
public void parseJSONData() {
CategoryAPI = Utils.MenuList + Cat_ID;
clearData();
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json = new JSONObject(str);
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
message = json2.getString("message");
if (status.equals("1")) {
JSONObject data = json.getJSONObject("data");
JSONArray school = data.getJSONArray("menu_groups");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
Category_ID.add(object.getString("id"));
Category_name.add(object.getString("title"));
Category_image.add(object.getString("image"));
}
}
else
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You are calling parseJSONData() in doInbackground and you have this
Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); // in parseJSONData()
you cannot update ui from doInbackground. You need to update ui on the ui thread. Return result in doInbackground. In onPostExecute update ui.

Async Task android

I have a Login page where I want to authenticate the username and password from the database on the network. The problem is while doing the AsyncTask I want to return the username and password values. But this is not happening.
How do I return the values? Here is my login page code.
public class Login extends Activity {
Integer aaa=0;
Button b,b2;
RelativeLayout r;
TextView t, t2;
String str1, str2, username, password;
String A = null, B = null;
EditText et1, et2;
Dialog myDialog;
String FILENAME = "http://animsinc.com/query.php";
protected ProgressDialog dialog;
protected Handler h;
static InputStream in = null;
static JSONObject jObj = null;
static String json = "";
private static final String TAG_ID = "id";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_in);
Display display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight() / 4;
r = (RelativeLayout) findViewById(R.id.RL);
RelativeLayout.LayoutParams r = new RelativeLayout.LayoutParams(width,
height);
t = (TextView) findViewById(R.id.textView1);
t2 = (TextView) findViewById(R.id.textView2);
t.setOnClickListener(link);
t2.setOnClickListener(fgtpass);
et1 = (EditText) findViewById(R.id.editText1);
et2 = (EditText) findViewById(R.id.editText2);
b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(temp);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((et1.getText().length() == 0)
|| (et2.getText().length() == 0))
{
Toast.makeText(getApplicationContext(),
"Please enter correct details",Toast.LENGTH_LONG)
.show();
} else {
dialog = ProgressDialog.show(Login.this, "Loading",
"Please Wait...");
/* h = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
dialog.dismiss();
}
};
new Thread() {
#Override
public void run() {
super.run();
String st=startDownload();
try {
Thread.sleep(3000);
h.sendEmptyMessage(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();*/
Toast.makeText(getApplicationContext(),""+st,Toast.LENGTH_LONG).show();
String st=startDownload();
Toast.makeText(getApplicationContext(),"aaa="+aaa, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),""+st, Toast.LENGTH_LONG).show();
}
if ((et1.getText().toString().equals(username))&& (et2.getText().toString().equals(password)))
{
Intent openStartingPoint = new Intent(Login.this,
UserActivity.class);
startActivity(openStartingPoint);
}
}
});
}
private
String startDownload() {
String C = null;
new AppTask().execute(FILENAME);
aaa++;
return C;
}
private View.OnClickListener temp = new View.OnClickListener() {
public void onClick(View V) {
Intent openStartingPoint = new Intent(Login.this,
UserActivity.class);
startActivity(openStartingPoint);
}
};
private View.OnClickListener link = new View.OnClickListener() {
public void onClick(View V) {
Intent openStartingPoint = new Intent(Login.this,
ContactDetails.class);
startActivity(openStartingPoint);
}
};
private View.OnClickListener fgtpass = new View.OnClickListener() {
public void onClick(View V) {
myDialog = new Dialog(Login.this);
myDialog.setContentView(R.layout.emailpop);
myDialog.setTitle("Forgot Password");
myDialog.setCancelable(true);
// for save
Button ok = (Button) myDialog.findViewById(R.id.button1);
ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
myDialog.dismiss();
}
});
myDialog.show();
}
};
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
public class AppTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... params) {
String is = null;
str1 = et1.getText().toString();
str2 = et2.getText().toString();
if (str1.length() > 0 && str2.length() > 0) {
A = str1;
B = str2;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://animsinc.com/query.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("username", str1));
nameValuePairs.add(new BasicNameValuePair("password", str2));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = EntityUtils.toString(entity);
JSONArray jArray = new JSONArray(is);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
username = jObject.getString("username");
password = jObject.getString("password");
aaa++;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return username;
}
}
}
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
So return value in doInBackground() , receive it in onPostExecute() and update ui accordingly.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeTest(MainActivity.this,result,1000).show();
//set result to textview
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// result is the value you return from doInBackground
String username = result;
}

Categories

Resources