Async Task android - 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;
}

Related

how to refresh listview after asynctask android

I have one page timeline like Facebook (there are EditText and Button), it has 2 async task. The first one is used to send parameter to remote server, the second one to load data json from URL. Actually first time, program will load JSON on the listview with async, then if I wanna update status after click Button then it will insert to table on the remote server. Both of them work successfully. But I have a little problem : after click button (update status) I want to refresh my listview. I have added the code on event click button, and then added onPostExecute (Class TheTask). After I send parameter, listview does not reload contents again. Can somebody help me to solve this problem ?
my source code :
public class Timeline extends Activity {
private static String BaseUrl="";
private String status;
final int PROGRESS_DIALOG=1;
private ProgressBar pb;
ViewConnection connection;
ArrayList<URLPostClass> timelinelist=new ArrayList<URLPostClass>();
ArrayList<URLPostClass> arrtimeline=new ArrayList<URLPostClass>();
//ArrayList<String> arritemcategory;
ListView listview;
//ListViewAdapter ListViewAdapter;
#Override
protected Dialog onCreateDialog(int id) {
switch(id)
{
case PROGRESS_DIALOG:
ProgressDialog progress =new ProgressDialog(this);
progress.setMessage("Loading");
progress.setTitle("Memuat status");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setProgress(0);
progress.setMax(100);
return progress;
}
return super.onCreateDialog(id);
}
private class GetTimelineAyncTask extends AsyncTask<Hashtable<String,String>,Void,String> {
#Override
protected void onPreExecute() {
showDialog(PROGRESS_DIALOG);
super.onPreExecute();
}
#Override
protected String doInBackground(Hashtable<String, String>... params)
{
// TODO Auto-generated method stub
Hashtable ht=params[0];
String json=HelperHttp.getJSONResponseFromURL(BaseUrl, ht);
if(json!=null) {
parseJsonString(timelinelist,json);
}else{
return "No internet access";
}
return json;
}
protected void parseJsonString(ArrayList<URLPostClass> timelinelistjs,String json){
try {
JSONObject jsonObj = new JSONObject(json);
JSONArray array = jsonObj.getJSONArray("listtimeline");
URLPostClass.setlength(array.length());
for (int i=0;i<array.length();i++){
JSONObject js=array.getJSONObject(i);
URLPostClass timeline=new URLPostClass(js.getString("IdTimeline"),
js.getString("NamaSales"),
js.getString("JenisStatus"),
js.getString("Remark"),
js.getString("TgglInsert"),
js.getString("Path"));
timelinelistjs.add(timeline);
}
}catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result){
if(result=="SUCCESS")
{
}else{
DecimalFormat formatter = new DecimalFormat("#,###,###");
JSONObject jObject = null;
Context mContext = null;
try {
jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("listtimeline");
for (int i=0; i < jArray.length(); i++)
{
JSONObject oneObject=jArray.getJSONObject(i);
URLPostClass timeline=new URLPostClass(oneObject.getString("IdTimeline"),
oneObject.getString("NamaSales"),
oneObject.getString("JenisStatus"),
oneObject.getString("Remark"),
oneObject.getString("TgglInsert"),
oneObject.getString("Path"));
arrtimeline.add(timeline);
}
listview = (ListView) findViewById(R.id.listtimeline);
listview.setAdapter(new ListViewTimelineAdapter(getBaseContext(), arrtimeline));
}catch (JSONException e) {
e.printStackTrace();
}
}
removeDialog(PROGRESS_DIALOG);
super.onPostExecute(result);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeline);
Global.Timeline=this;
final RadioButton rbtnlisting=(RadioButton)findViewById(R.id.rbtnlisting);
final RadioButton rbtnclosing=(RadioButton)findViewById(R.id.rbtnclosing);
final RadioButton rbtnprospek=(RadioButton)findViewById(R.id.rbtnprospek);
final EditText edtstatus=(EditText)findViewById(R.id.edtstatus);
Button btnpost=(Button)findViewById(R.id.btnpost);
edtstatus.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
btnpost.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
rbtnlisting.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
rbtnclosing.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
rbtnprospek.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
listview = (ListView) findViewById(R.id.listtimeline);
pb=(ProgressBar)findViewById(R.id.progressBar1);
pb.setVisibility(View.GONE);
connection = new ViewConnection(getBaseContext());
if (connection.isConnectingToInternet())
{
btnpost.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (edtstatus.getText().length()>5) {
pb.setVisibility(View.VISIBLE);
TheTask async=new TheTask();
async.execute("ccc");
}else {
Toast.makeText(getBaseContext(), "Your status is too short", Toast.LENGTH_LONG).show();
}
}
});
BaseUrl="http://xxx.xxx.xxx.xxx/dummy/gettimeline.php";
executeAsyncTask();
}else {
// Internet connection is not present
LayoutInflater li = LayoutInflater.from(Timeline.this);
final View inputdialogcustom = li.inflate(R.layout.activity_confirm_connection, null);
AlertDialog.Builder alert = new AlertDialog.Builder(Timeline.this);
alert.setView(inputdialogcustom);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
alert.show();
}
}
class TheTask extends AsyncTask<String, Integer, Double>
{
#Override
protected Double doInBackground(String... params) {
postData(params[0]);
return null;
}
protected void onPostExecute(Double result) {
// TODO Auto-generated method stub
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Status telah diposting !", Toast.LENGTH_LONG).show();
BaseUrl="http://xxx.xxx.xxx.xxx/dummy/gettimeline.php"; // I PUT ON HERE
executeAsyncTask();
}
protected void onProgressUpdate(Integer... progress){
pb.setProgress(progress[0]);
}
public void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
RadioButton rbtnlisting=(RadioButton)findViewById(R.id.rbtnlisting);
RadioButton rbtnclosing=(RadioButton)findViewById(R.id.rbtnclosing);
RadioButton rbtnprospek=(RadioButton)findViewById(R.id.rbtnprospek);
EditText edtstatus=(EditText)findViewById(R.id.edtstatus);
if (edtstatus.getText().length()>5) {
RadioGroup radiotipe = (RadioGroup) findViewById(R.id.radiotipe);
int selectedId = radiotipe.getCheckedRadioButtonId();
RadioButton rbtnselected=(RadioButton) findViewById(selectedId);
status=rbtnselected.getText().toString();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxx.xxx.xxx.xxx/dummy/insert.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("idsales",OtherClass.getIdSales().toString()));
nameValuePairs.add(new BasicNameValuePair("jenis", status));
nameValuePairs.add(new BasicNameValuePair("remark", edtstatus.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("path", "coba coba"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response=httpclient.execute(httppost);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
// TODO Auto-generated catch block
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
Toast.makeText(getBaseContext(), "Your status is too short", Toast.LENGTH_LONG).show();
}
}
}
private void executeAsyncTask(){
Hashtable<String,String> ht=new Hashtable<String,String>();
GetTimelineAyncTask async=new GetTimelineAyncTask();
Hashtable[] ht_array={ht};
async.execute(ht_array);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.tab_sport, menu);
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.menutimeline, menu);
return super.onCreateOptionsMenu(menu);
}
#SuppressLint("NewApi")
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.menulogout:
//Toast.makeText(getBaseContext(), "test", Toast.LENGTH_LONG).show();
//View view = item.getActionView();
//final EditText edtsearchitem=(EditText)view.findViewById(R.id.edtsearchitem);
OtherClass.setIdSales("");
Global.Timeline.finish();
Intent MyIntentDetailItem=new Intent(getBaseContext(), MainActivity.class);
startActivity(MyIntentDetailItem);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Here you have to create global Adapter and call to notifydatasetchanged() using adapter
Declare globally
ListViewTimelineAdapter adapter=null;
and replace
listview = (ListView) findViewById(R.id.listtimeline);
listview.setAdapter(new ListViewTimelineAdapter(getBaseContext(), arrtimeline));
code with
listview = (ListView) findViewById(R.id.listtimeline);
adapter=new ListViewTimelineAdapter(getBaseContext(), arrtimeline);
listview.setAdapter(adapter);
adapter.NotifyDatasetChanged();
thats it...and when ever you want to refresh list just write
adapter.NotifyDatasetChanged();
and listview reloaded...
This may become handy in your situation:
myListView.invalidateViews();
Original answer with some other ways explained can be found here:
How to refresh Android listview?
Hope it helps.

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 show toast in getDataTaskmethod? [duplicate]

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

AsyncTask, HttpClient and ProgressDialog

I'm creating a AsyncTask to login user to a server.
The login works fine, but the ProgressDialog does not show until the end of the process.
As soon as the user taps the button, the UI freezes, and my dialog does not show up.
I appreciate any help. Here's my code.
public class MyApp extends Activity {
private ProgressDialog dialogo = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button loginButton = (Button) findViewById(R.id.btnLogin);
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences preferencias = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String webAddress = preferencias.getString("webAddress", "");
if (webAddress.isEmpty()) {
Toast.makeText(getBaseContext(), "Please, configure a Web Address.", Toast.LENGTH_LONG).show();
} else {
EditText edtUsername = (EditText) findViewById(R.id.edtUsername);
EditText edtPassword = (EditText) findViewById(R.id.edtPassword);
HashMap<String, String> parametros = new HashMap<String, String>();
parametros.put("username", edtUsername.getText().toString());
parametros.put("password", edtPassword.getText().toString());
Requisicao requisicao = new Requisicao(parametros);
AsyncTask<String, Void, String> resposta = requisicao.execute(webAddress + "/login");
try {
Toast.makeText(getBaseContext(), resposta.get(), Toast.LENGTH_LONG).show();
} catch (InterruptedException e) {
Toast.makeText(getBaseContext(), "InterruptedException (login)", Toast.LENGTH_LONG).show();
} catch (ExecutionException e) {
Toast.makeText(getBaseContext(), "ExecutionException (login)", Toast.LENGTH_LONG).show();
}
}
}
});
ImageView engrenagem = (ImageView) findViewById(R.id.imgEngrenagem);
engrenagem.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent preferenciasActivity = new Intent(getBaseContext(), Preferencias.class);
startActivity(preferenciasActivity);
}
});
}
public class Requisicao extends AsyncTask<String, Void, String> {
private final HttpClient clienteHttp = new DefaultHttpClient();
private String resposta;
private HashMap<String, String> parametros = null;
public Requisicao(HashMap<String, String> params) {
parametros = params;
}
#Override
protected void onPreExecute() {
dialogo = new ProgressDialog(MyApp.this);
dialogo.setMessage("Aguarde...");
dialogo.setTitle("Comunicando com o servidor");
dialogo.setIndeterminate(true);
dialogo.setCancelable(false);
dialogo.show();
}
#Override
protected String doInBackground(String... urls) {
byte[] resultado = null;
HttpPost post = new HttpPost(urls[0]);
try {
ArrayList<NameValuePair> paresNomeValor = new ArrayList<NameValuePair>();
Iterator<String> iterator = parametros.keySet().iterator();
while (iterator.hasNext()) {
String chave = iterator.next();
paresNomeValor.add(new BasicNameValuePair(chave, parametros.get(chave)));
}
post.setEntity(new UrlEncodedFormEntity(paresNomeValor, "UTF-8"));
HttpResponse respostaRequisicao = clienteHttp.execute(post);
StatusLine statusRequisicao = respostaRequisicao.getStatusLine();
if (statusRequisicao.getStatusCode() == HttpURLConnection.HTTP_OK) {
resultado = EntityUtils.toByteArray(respostaRequisicao.getEntity());
resposta = new String(resultado, "UTF-8");
}
} catch (UnsupportedEncodingException e) {
} catch (Exception e) {
}
return resposta;
}
#Override
protected void onPostExecute(String param) {
dialogo.dismiss();
}
}
}
Try to comment out resposta.get() call in the button listener. I guess it just blocks the main UI thread untill the task is finished.
Couple things. First of all, don't make an instance for ASyncClass because you can only ever call it once, as per the android documentation. So execute like this: new Requisicao().execute(webAddress + "/login");
Also, instead of calling requisicao.get(), which will, again according to documentation "Waits if necessary for the computation to complete, and then retrieves its result" (also known as blocking), from within your async class add an override:
protected void onProgressUpdate(Long... progress) {
CallBack(progress[0]); // for example
}
Where CallBack is a function in your UI thread which will handle processing your progress long, or string, or whatever else you want to throw back. Mind you, your ASync class will have to be defined within the UI class instead of separately.
move your
private ProgressDialog dialogo = null;
into the AsyncTask's fields as you did it with HTTPClient because you don't
seem to use it anywhere and
try to create your dialog in the constructor
public Requisicao(HashMap<String, String> params) {
parametros = params;
dialogo = new ProgressDialog(MyApp.this);
}
in postExecute
if (dialogo .isShowing()) {
dialogo .dismiss();
}
hope it helps.

How to start and finish progressBar dynamically in android

When I skip second activity class from first activity class, I will start imageprocessing on certain image in second activity and then until new image comes to screen I wnt to start progress bar and then finish when the new image comes to screen. How can I do this ?
Use ProgreaaDialog and AsyncTask. you wil get your soultion
Use AsyncTask in doBackInGroundProcess do image processing. and in doPostExecute() exit or cancel the progress dialog
have a look on the sample code.
To start AsyncTsk use new ProgressTask().execute(null); from the activity where you want to do image processing.
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
List<Message> titles;
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.show();
}
#Override
protected void onPostExecute(final Boolean success) {
List<Message> titles = new ArrayList<Message>(messages.size());
for (Message msg : messages){
titles.add(msg);
}
MessageListAdapter adapter = new MessageListAdapter(activity, titles);
activity.setListAdapter(adapter);
adapter.notifyDataSetChanged();
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
}
}
protected Boolean doInBackground(final String... args) {
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();
return true;
} catch (Exception e){
Log.e("tag", "error", e);
return false;
}
}
}
}
Have a look here
Try using Async task as shown below:
try{
class test extends AsyncTask{
TextView tv_per;
int mprogress;
Dialog UpdateDialog = new Dialog(ClassContext);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
mprogress = 0;
UpdateDialog.setTitle(getResources().getString(R.string.app_name));
UpdateDialog.setContentView(R.layout.horizontalprogressdialog);
TextView dialog_message = (TextView)UpdateDialog.findViewById(R.id.titleTvLeft);
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
dialog_message.setText(getResources().getString(R.string.dialog_retrieving_data));
dialog_message.setGravity(Gravity.RIGHT);
UpdateDialog.setCancelable(false);
UpdateDialog.show();
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Object... values) {
// TODO Auto-generated method stub
ProgressBar update = (ProgressBar)UpdateDialog.findViewById(R.id.horizontalProgressBar);
update.setProgress((Integer) values[0]);
int percent = (Integer) values[0];
if(percent>=100)
{
percent=100;
}
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
tv_per.setText(""+percent);
}
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
//your code
}
super.onPostExecute(result);
UpdateDialog.dismiss();
}
}
new test().execute(null);
}
catch(Exception e)
{
e.printStackTrace();
}
Here is a method which when called starts a progressbar
private void downloadText(String urlStr) {
final String url = urlStr;
progressDialog = ProgressDialog.show(this, "", "Trying to register...");
Log.i("First string", urlStr);
try{
new Thread () {
public void run() {
int BUFFER_SIZE = 2000;
InputStream in = null;
try{
msg = Message.obtain();
msg.what=1;
}catch(Exception e)
{
}
try {
in = openHttpConnection(url);
InputStreamReader isr = new InputStreamReader(in);
int charRead;
text = "";
char[] inputBuffer = new char[BUFFER_SIZE];
while ((charRead = isr.read(inputBuffer))>0)
{
//---convert the chars to a String---
String readString =
String.copyValueOf(inputBuffer, 0, charRead);
text += readString;
inputBuffer = new char[BUFFER_SIZE];
}
Bundle b = new Bundle();
b.putString("text", text);
msg.setData(b);
in.close();
}catch (Exception e) {
//////////////////////////////////////
e.printStackTrace();
}
try{
messageHandler.sendMessage(msg);
}catch(Exception e)
{
}
}
}.start();
}catch(Exception e)
{
}
}
and here is the handler code
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
try{
super.handleMessage(msg);
switch (msg.what) {
case 1:
{
break;
}
}
progressDialog.dismiss();
}catch(Exception e)
{
}
}
};
Try this way
first Intialize your ProgressDialog
progressDialog = ProgressDialog.show(this, "", "Trying to ...");
then start a new thread in which you can write your code which needs to be executed
and finally in the handler handle the code and end the progessDialog

Categories

Resources