How to add progress bar until loop execution is finished? - android

I am developing an android app where I need to show a ProgressBar until the loop execution is finished. After execution it will go to the nextActivity.
here is my java code
public class Image_Recognition extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image__recognition);
Button btnNextPage = (Button) findViewById(R.id.btnNextPage);
btnNextPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<TextBlock> items = textRecognizer.detect(frame);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < items.size(); ++i) {
TextBlock item = items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
stringBuilder.append('.');
txtResult.setText(stringBuilder.toString());
str = stringBuilder.toString();
Intent myintent = new Intent(Image_Recognition.this, ReminderAddActivity.class);
myintent.putExtra("translate", str);
startActivity(myintent);
}
});
}
//}
}

You can try with this.
final ProgressDialog dialog = new ProgressDialog(Image_Recognition.this);
btnNextPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.show(Image_Recognition.this, "", "Please wait...", true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!textRecognizer.isOperational())
Log.e("ERROR", "Detector dependencies are not yet available");
else {
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<TextBlock> items = textRecognizer.detect(frame);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < items.size(); ++i) {
TextBlock item = items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
stringBuilder.append('.');
txtResult.setText(stringBuilder.toString());
str = stringBuilder.toString();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.dismiss();
dialog.setCancelable(true);
Intent myintent = new Intent(Image_Recognition.this, ReminderAddActivity.class);
myintent.putExtra("translate", str);
startActivity(myintent);
}
});
}
},5000);

You have two problems here.
ProgressBar, which you can use ProgressDialog or a ProgressBar in your XML and show it, while hiding the rest of your IU.
Blocking the UI
You are running your loop directly from you click listener, which means that you will block your UI and even if you show some sort of progress, it will be blocked till your loop is over, you need to start a thread and run your loop in.
Here's a not very clean version of you click listener impl
final ProgressDialog dialog = new ProgressDialog(Image_Recognition.this);
dialog.show();
new Thread(new Runnable() {
#Override
public void run() {
TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<TextBlock> items = textRecognizer.detect(frame);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < items.size(); ++i) {
TextBlock item = items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
stringBuilder.append('.');
txtResult.setText(stringBuilder.toString());
str = stringBuilder.toString();
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.dismiss();
Intent myintent = new Intent(Image_Recognition.this, ReminderAddActivity.class);
myintent.putExtra("translate", str);
startActivity(myintent);
}
});
}
}).start();

You could use Async Task and run your loop in doInBackground()
class MyTask extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
public MyTask(ProgressDialog pd){
this.pd=pd;
}
#Override
protected void onPreExecute () {
super.onPreExecute();
pd.setMessage("Uploading . . .");
pd.show();
pd.setCancelable(false);
}
#Override
protected Void doInBackground (Void...voids){
for(int i=0;i<10000000;i++){
System.out.print(i);
}
return null;//download file
}
#Override
protected void onPostExecute (Void aVoid){
super.onPostExecute(aVoid);
pd.dismiss();
}
}
and in activity call new MyTask(pd).execute();

Related

Async Task error: no text is given when user had inserted a string

Solved: Could someone check my codes and help? I am using an emotion recognition API that generate strings from text input from user. I am learning to use AsyncTask to load the result but having an error showed "No text given" even when the user inserted a string at edittext, the error is detected from the 'catch' exception at the try{} block in doInBackground method.
public class Main3Activity extends AppCompatActivity {
private TextView textmain1, textmain2;
private EditText editText;
private Button submitBtn;
private String userInputText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
textmain1 = (TextView) findViewById(R.id.detected3);
textmain2 = (TextView) findViewById(R.id.sentences3);
editText = (EditText) findViewById(R.id.edittext3);
submitBtn = (Button) findViewById(R.id.submitBtn3);
userInputText = editText.getText().toString();
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute(userInputText);
}
});
}
private class MyAsyncTask extends AsyncTask<String, Integer, Boolean> {
private String detectedResponse, sentencesResponse;
private ProgressBar progressBar;
#Override
protected void onPreExecute() {
progressBar = (ProgressBar) findViewById(R.id.progressbar);
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected Boolean doInBackground(String... strings) {
String myString = strings[0];
try {
List<ToneScore> documentTones = new ArrayList<>();
List<SentenceAnalysis> sentenceDetectedTones = new ArrayList<>();
IamAuthenticator authenticator = new IamAuthenticator(authenticator);
ToneAnalyzer toneAnalyzer = new ToneAnalyzer("2020-02-22", authenticator);
toneAnalyzer.setServiceUrl(url);
ToneOptions toneOptions = new ToneOptions.Builder().text(myString).build();
ToneAnalysis toneAnalysis = toneAnalyzer.tone(toneOptions).execute().getResult();
documentTones = toneAnalysis.getDocumentTone().getTones();
if (documentTones == null || documentTones.isEmpty()) {
detectedResponse = "No tones are detected :(";
} else {
StringBuilder detectedTones = new StringBuilder();
for (ToneScore score : documentTones) {
if (score.getScore() > 0.5f) {
detectedTones.append(score.getToneName()).append(" \n").append(score.getScore()).append("\n\n");
}
}
detectedResponse = detectedTones.toString();
}
sentenceDetectedTones = toneAnalysis.getSentencesTone();
if (sentenceDetectedTones == null || sentenceDetectedTones.isEmpty()) {
sentencesResponse = "Oops! No sentence analysis is available for this one";
} else {
StringBuilder sentenceTones = new StringBuilder();
for (SentenceAnalysis sentenceAnalysis : sentenceDetectedTones) {
List<ToneScore> singleScoreBlock = sentenceAnalysis.getTones();
for (ToneScore toneScore : singleScoreBlock) {
if (toneScore.getScore() > 0.5) {
sentenceTones.append("\"").append(sentenceAnalysis.getText()).append("\"");
sentenceTones.append("\n").append(toneScore.getToneName()).append(": ").append(toneScore.getScore()).append("\n\n");
}
}
}
sentencesResponse = sentenceTones.toString();
}
} catch (ArrayIndexOutOfBoundsException | IllegalArgumentException | ServiceResponseException e) {
Main3Activity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(Main3Activity.this, "API error here: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
publishProgress();
return true;
}
#Override
protected void onPostExecute(Boolean s) {
progressBar.setVisibility(View.GONE);
editText.setText("");
if (s.equals(true)) {
textmain1.setText(detectedResponse);
textmain2.setText(sentencesResponse);
} else {
Toast.makeText(Main3Activity.this, "Error :(", Toast.LENGTH_SHORT).show();
}
}
}
}
You have to get the text on click of the button
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userInputText = editText.getText().toString();
MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute(userInputText);
}
});

Problem showing progress dialog while running code

I am trying to show a progress dialog with percentage while executing a long running code, I used AsyncTask for this purpose but it did not work, the functionality is as follow: I get the array paths of all gallery images and then I process these images and extract the descriptor vector of each image and convert it to JSON string and then store these strings into sqlite, but my code takes lot of time( few minutes ), so what I need is to show a progress dialog with percentage in order to know the start and end of the task, this task I need to start it when I press a button. Below is my code:
public void FillDataBase(){
ArrayList<String> paths = getFilePaths();
for (int i = 0; i < paths.size(); i++) {
Mat mat = new Mat();
BitmapFactory.Options bmOptions1 = new BitmapFactory.Options();
//bmOptions1.inSampleSize=4;
Bitmap bitmap0 = BitmapFactory.decodeFile(paths.get(i).toString(), bmOptions1);
Bitmap bitmap = getRotated(bitmap0, paths.get(i).toString());
//Utils.bitmapToMat(bitmap, mat);
Mat matRGB = new Mat();
Utils.bitmapToMat(bitmap, matRGB);
Imgproc.cvtColor(matRGB, mat, Imgproc.COLOR_RGB2GRAY);
org.opencv.core.Size s2 = new Size(3, 3);
Imgproc.GaussianBlur(mat, mat, s2, 2);
FeatureDetector detector2 = FeatureDetector.create(FeatureDetector.ORB);
MatOfKeyPoint keypoints2 = new MatOfKeyPoint();
detector2.detect(mat, keypoints2);
DescriptorExtractor extractor2 = DescriptorExtractor.create(DescriptorExtractor.ORB);
Mat descriptors2 = new Mat();
extractor2.compute(mat, keypoints2, descriptors2);
// String matimage = matToJson(mat);
String matkeys= keypointsToJson(keypoints2);
String desc = matToJson(descriptors2);
mat m = new mat(desc, matkeys);
DataBaseHandler db = new DataBaseHandler(getApplicationContext());
db.addmat(m);
}
Asynctask Code (I call the FillDatabase() in public void run of the thread):
private class ProgressTask extends AsyncTask<Void,Void,Void>{
private int progressStatus=0;
private Handler handler = new Handler();
// Initialize a new instance of progress dialog
private ProgressDialog pd = new ProgressDialog(RGBtoGrey.this);
#Override
protected void onPreExecute(){
super.onPreExecute();
pd.setIndeterminate(false);
// Set progress style horizontal
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// Set the progress dialog background color
pd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.YELLOW));
// Make the progress dialog cancellable
pd.setCancelable(true);
// Set the maximum value of progress
pd.setMax(100);
// Finally, show the progress dialog
pd.show();
}
#Override
protected Void doInBackground(Void...args){
// Set the progress status zero on each button click
progressStatus = 0;
// Start the lengthy operation in a background thread
new Thread(new Runnable() {
#Override
public void run() {
FillDataBase();
while(progressStatus < 100){
// Update the progress status
progressStatus +=1;
// Try to sleep the thread for 20 milliseconds
try{
Thread.sleep(20);
}catch(InterruptedException e){
e.printStackTrace();
}
// Update the progress bar
handler.post(new Runnable() {
#Override
public void run() {
// Update the progress status
pd.setProgress(progressStatus);
// If task execution completed
if(progressStatus == 100){
// Dismiss/hide the progress dialog
pd.dismiss();
}
}
});
}
}
}).start(); // Start the operation
return null;
}
protected void onPostExecute(){
// do something after async task completed.
}
And finally i call the Asynctask like this:
testButton0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new ProgressTask().execute();
}
});
You could do something like this:
private static class InsertAllPersonsToFirebaseTask extends AsyncTask<Void, Float, Void> {
private List<Person> personList;
private ElasticDownloadView mElasticDownloadView;
private DatabaseReference mDatabase, pushedKey;
private Person person;
public InsertAllPersonsToFirebaseTask(List<Person> personList, ElasticDownloadView mElasticDownloadView) {
this.personList = personList;
this.mElasticDownloadView = mElasticDownloadView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (mElasticDownloadView != null) {
this.mElasticDownloadView.setVisibility(View.VISIBLE);
this.mElasticDownloadView.startIntro();
}
}
#Override
protected Void doInBackground(Void... voids) {
mDatabase = FirebaseDatabase.getInstance().getReference();
for (int i = 0; i < personList.size(); i++){
pushedKey = mDatabase.child("Persons").push();
person = new Person();
person.setPersonId(System.currentTimeMillis());
person.setName(personList.get(i).getName());
pushedKey.setValue(person);
//This line is for update the onProgressUpdate() method
publishProgress(((i+1)/(float)personList.size()* 100));
if (isCancelled()){
break;
}
}
return null;
}
#Override
protected void onProgressUpdate(Float... progress) {
if (mElasticDownloadView != null){
mElasticDownloadView.setProgress(progress[0]);
}
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (mElasticDownloadView != null){
mElasticDownloadView.setVisibility(View.GONE);
}
}
}
You can use any type of progressbar. I have used ElasticDownloadview progressbar.
Then:
testButton0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new InsertAllPersonsToFirebaseTask(personArrayList,mElasticDownloadView).execute();
}
});

Android progress bar for method

I have a custom method of my class that (on my Android phone) takes 2-3 second to finish, and I would like to surround it with a progress bar.
Here is my method:
public void getQuestionsForSelectedCategory(){
ArrayList<Question> temp = (ArrayList<Question>) this.clone();
ArrayList<Question> tempGroup;
this.clear();
for(int i=0;i<2;i++){
tempGroup = new ArrayList<Question>();
for(int j=0;j<temp.size();j++)
if((temp.get(j).getGroup()==i+1)&&(temp.get(j).getCategory().contains(category)||temp.get(j).getCategory().equals("*")))
tempGroup.add(temp.get(j));
getQuestionsForSelectedGroup(tempGroup, numbersByGroup[i], pointsByGroup[i]);
}
tempGroup = new ArrayList<Question>();
for(int i=0;i<temp.size();i++){
int a = temp.get(i).getGroup();
if((a==3||a==4||a==5||a==6||a==7))
if(temp.get(i).getCategory().contains(category)||temp.get(i).getCategory().equals("*"))
tempGroup.add(temp.get(i));
}
Collections.shuffle(tempGroup);
getQuestionsForSelectedGroup(tempGroup, numbersByGroup[2], pointsByGroup[2]);
if(category.equals("C")){
tempGroup = new ArrayList<Question>();
for(int i=0;i<temp.size();i++)
if(temp.get(i).getCategory().equals(category))
tempGroup.add(temp.get(i));
getQuestionsForSelectedGroup(tempGroup, 10, 30);
}
}
And here is what I try to do:
barProgressDialog = new ProgressDialog(this);
barProgressDialog.setTitle("Preparing Test");
barProgressDialog.setMessage("Preparing Test");
barProgressDialog.setProgressStyle(barProgressDialog.STYLE_HORIZONTAL);
barProgressDialog.setProgress(0);
barProgressDialog.setMax(100);
barProgressDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
getQuestionsForSelectedCategory();
while (barProgressDialog.getProgress() <= barProgressDialog.getMax()) {
updateBarHandler.post(new Runnable() {
public void run() {
barProgressDialog.incrementProgressBy(2);
}
});
if (barProgressDialog.getProgress() == barProgressDialog.getMax()) {
barProgressDialog.dismiss();
}
}
} catch (Exception e) {
}
}
}).start();
}
For the current code the progress bar fills up to 100 but it does nothing.
You could use an AsyncTask to achieve this, whilst publishing your progress during the task.
AsyncTask<Void, Integer, Void> task = new AsyncTask<Void, Integer, Void>() {
#Override
protected Void doInBackground(Void... voids) {
getQuestionsForSelectedCategory();
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
barProgressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void aVoid) {
barProgressDialog.dismiss();
}
}
task.execute();
Ensure your getQuestionsForSelectedCategory and getQuestionsForSelectedGroup methods are inside the AsyncTask and within the loops you can call publishProgress(int progress) to update the progress dialog.

IllegalStateException in AsyncTask. The content of adapter has changed but listview did not receive a notification

I am working on TCP socket. I receive data for every 1 sec from server and I need to display it on screen in ListView.
For this I used AsyncTask.
But I am frequently getting IllegalStateException error
My code:
Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
finalizer = new Runnable() {
public void run() {
try {
if (navBool) {
runOnUiThread(new Runnable() {
public void run() {
new RetriveStock().execute(); // AsyncTask.
}
});
}
} catch (Exception e) {
}
}
};
handler.post(finalizer);
}
};
timer.schedule(doAsynchronousTask, 0, 1000);
// AsyncTask class
public class RetriveStock extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
message = client.clientReceive(1); // Here I receive data from server and stores it in "message" string variable.
printJson(); // FUNCTION WHICH UPDATE VALUES IN 'obj' OBJECT
runOnUiThread(new Runnable() {
#Override
public void run() {
updateList();// FUNCTION WHICH UPDATE THE LISTVIEW UI.
adb.notifyDataSetChanged();
}
});
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
if (adb != null) {
lv.invalidateViews();
lv.setAdapter(adb);
adb.notifyDataSetChanged();
lv.requestLayout();
}
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
// function which update values in JSON.
public void printJson() {
try {
JSONArray jsonArray = new JSONArray(message);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
String symbol = json.getString("Symbol_En");
User obj = new User();
boolean checkSymbol = false;
for (int j = 0; j < list.size(); j++) {
obj = list.get(j);
if (obj.getSymbol().equalsIgnoreCase(symbol)) {
checkSymbol = true;
break;
}
}
if (!checkSymbol) {
obj = new User();
obj.Symbol_En = json.getString("Symbol_En");
obj.Symbol_Ar = json.getString("Symbol_Ar");
obj.AskPrice = json.getString("Ask");
obj.BidPrice = json.getString("Bid");
obj.AskQuantity = json.getString("AskQuantity");
obj.High = json.getString("High");
obj.Low = json.getString("Low");
obj.Open = json.getString("Open");
obj.Close = json.getString("Close");
obj.PerChange = json.getString("PerChange");
obj.NetChange = json.getString("NetChange");
obj.Volume = json.getString("Volume");
obj.Ltp = json.getString("LTP");
obj.TimeStamp = json.getString("TimeStamp");
obj.symbolId = json.getString("Id");
list.add(obj);
} else {
obj.Symbol_En = json.getString("Symbol_En");
obj.AskPrice = json.getString("Ask");
obj.BidPrice = json.getString("Bid");
obj.High = high + "";
obj.Low = low + "";
obj.Open = json.getString("Open");
obj.Close = json.getString("Close");
obj.PerChange = json.getString("PerChange");
obj.NetChange = json.getString("NetChange");
obj.Volume = json.getString("Volume");
obj.Ltp = json.getString("LTP");
obj.TimeStamp = json.getString("TimeStamp");
obj.symbolId = json.getString("Id");
}
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
// function which update LISTVIEW UI.
public void updateList() {
adb = new ArrayAdapter<User>(DefaultMarketWatch.this,
R.layout.rssitemview, list) {
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
View view = convertView;
try {
if (null == view) {
LayoutInflater vi = (LayoutInflater) DefaultMarketWatch.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.rssitemview, null);
}
final User u = list.get(position);
if (null != u) {
final TextView title = (TextView) view
.findViewById(R.id.symbol);
final TextView persend = (TextView) view
.findViewById(R.id.persent);
final TextView ltp = (TextView) view
.findViewById(R.id.ltp);
final TextView high = (TextView) view
.findViewById(R.id.high);
final TextView low = (TextView) view
.findViewById(R.id.low);
final TextView persendBold = (TextView) view
.findViewById(R.id.persent_bold);
final TextView persendSup = (TextView) view
.findViewById(R.id.persent_sup);
ltp.setText(u.getLtp());
title.setText(u.getSymbol());
high.setText(u.getHigh());
low.setText(u.getLow());
persend.setText(u.getPerChange());
}
} catch (Exception e) {
e.printStackTrace();
}
return view;
}
};
}
Your log says
The content of the adapter is changed but listview did not receive notification. make sure content of your adapter is not modified from background thread but only from ui thread.
You have updateList() // FUNCTION WHICH UPDATE THE LISTVIEW UIin doInBackground. doInbackground is invoked on the background thread. You need to update ui on the Ui thread.
Use runOnUiThread which is method of activity or return result in doInbackground and update listview in onPostExecute

Handling Activity stack through application programmatically

I have four activities in my application A-->B-->C-->D.
I write a My own class MyActivity which extends Activity class. I write this class to handle activity stack.This class has two methods addActivitiyTostack() and getActivityFromStack()
I used a stack for storing activities.
All other activities are extends this class.
When I moved from one activity to other using intent it added to stack.
And when I moved backword activity gets popped up.
I can correctly add activities to stack, But I have problem in popping the activities.
also I have Logout Button on all activities, OnClick of this button I want to close the application how to implement it? Anybody know how to handle activity stack in Android.
This is my code.
package com.example.iprotect;
import java.util.Enumeration;
import java.util.Stack;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MyActivity extends Activity {
private static Stack<Activity> stack = new Stack<Activity>();
static int top=0;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addActivityToStack(this);
}
public static void addActivityToStack(MyActivity myActivity) {
// TODO Auto-generated method stub
stack.push(myActivity);
for (int i =0; i< stack.size() ; i++) {
Activity act=stack.get(i);
Log.i("Element in stack", ""+act);
}
}
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
//getActivityFromStack();
//logoutFromApplication();
}
public static void logoutFromApplication() {
// TODO Auto-generated method stub
Enumeration<Activity> enm=stack.elements();
while(enm.hasMoreElements())
{
Activity act=enm.nextElement();
stack.pop();
}
}
public static Activity getActivityFromStack() {
return stack.pop();
}
}
A-->
public class WebServiceActivity extends MyActivity{
EditText editText1, editText2;
Button button;
String response = "";
String email, password;
public final Pattern EMAIL_ADDRESS_PATTERN = Pattern
.compile(".+#.+\\.[a-z]+");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText1 = (EditText) findViewById(R.id.etEmail);
final EditText editText2 = (EditText) findViewById(R.id.etPassword);
button = (Button) findViewById(R.id.loginButton);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(editText1.getText().toString())) {
Toast.makeText(getApplicationContext(),
"please enter email id", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(editText2.getText().toString())) {
Toast.makeText(getApplicationContext(),
"please enter passwod", Toast.LENGTH_SHORT).show();
} else {
Boolean bool = EMAIL_ADDRESS_PATTERN.matcher(
editText1.getText().toString()).matches();
if (bool == true) {
} else {
Toast.makeText(getApplicationContext(),
"Invalid email id", Toast.LENGTH_SHORT).show();
}
email = editText1.getText().toString();
password = editText2.getText().toString();
// final ProgressDialog pd = ProgressDialog.show(
// WebServiceActivity.this, "Calling webservice...",
// "Please wait...", true, false);
final ProgressBar bar = (ProgressBar) findViewById(R.id.progressBar2);
bar.setVisibility(View.VISIBLE);
new AsyncTask<Void, Void, Void>() {
String r;
protected void onPreExecute() {
};
#Override
protected Void doInBackground(Void... params) {
r = invokeWebService();
return null;
};
protected void onPostExecute(Void result) {
bar.setVisibility(View.VISIBLE);
};
}.execute();
}
}
private String invokeWebService() {
String response = "";
try {
WebService webService = new WebService(
"http://sphinx-solution.com/iProtect/api.php?");
Map<String, String> params = new HashMap<String, String>();
params.put("action", "auth");
params.put("email", email);
params.put("password", password);
response = webService.WebGet("auth", params);
JSONObject jsonObject = new JSONObject(response);
String rr = jsonObject.optString("status");
if (TextUtils.equals(rr, "success")) {
Log.e("MSG", "status==success");
Intent intent = new Intent(WebServiceActivity.this,
SecondActivity.class);
//MyActivity.addActivityToStack(WebServiceActivity.this);
intent.putExtra("email", email);
intent.putExtra("password", password);
WebServiceActivity.this.startActivity(intent);
finish();
} else {
Log.e("MSG", "status ==failed");
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
});
}
}
B-->
public class SecondActivity extends MyActivity {
ListView listView;
String email1, password1;
ArrayList<JSONStructure> arrayList = new ArrayList<JSONStructure>();
String r;
String r1;
String tablename;
String rows;
JSONObject jsonObject;
String tablename2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_layout);
Intent intent = getIntent();
email1 = intent.getExtras().getString("email");
password1 = intent.getExtras().getString("password");
Button btn1 = (Button) findViewById(R.id.refreshbutton);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog pd = ProgressDialog.show(
SecondActivity.this, "Refresh List...",
"Please wait...", true, false);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
pd.dismiss();
r = invokeWebService();
return null;
}
protected void onPostExecute(Void result) {
};
}.execute();
}
});
Button btn = (Button) findViewById(R.id.logoutbutton);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog pd = ProgressDialog.show(
SecondActivity.this, "Calling webservice...",
"Please wait...", true, false);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
pd.dismiss();
return null;
}
#Override
protected void onPostExecute(Void result) {
Intent intent = new Intent(SecondActivity.this,
WebServiceActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
SecondActivity.this.startActivity(intent);
}
}.execute();
}
});
listView = (ListView) findViewById(R.id.listview1);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
JSONStructure jsonstructure = (JSONStructure) listView
.getAdapter().getItem(position);
final String tablename1 = jsonstructure.getTableName()
.toString();
Intent intent = new Intent(SecondActivity.this,
ProgressBarActivity.class);
//MyActivity.addActivityToStack(SecondActivity.this);
intent.putExtra("tablename", tablename1);
intent.putExtra("Rows", rows);
intent.putExtra("email", email1);
intent.putExtra("password", password1);
SecondActivity.this.startActivity(intent);
}
});
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
r = invokeWebService();
try {
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject(r);
jsonArray = jsonObject.getJSONArray("Records");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
tablename = c.optString("TABLE NAME");
rows = c.optString("Rows");
JSONStructure jsonStructure = new JSONStructure();
jsonStructure.setTableName(tablename);
jsonStructure.setRows(rows);
arrayList.add(jsonStructure);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (arrayList != null && arrayList.size() > 0) {
MyAdapter adapter = new MyAdapter(SecondActivity.this,
arrayList);
listView.setAdapter(adapter);
}
}
}.execute();
}
private String invokeWebService() {
String response = "";
try {
WebService webService = new WebService(
"http://sphinx-solution.com/iProtect/api.php?");
Map<String, String> params = new HashMap<String, String>();
params.put("action", "getTables");
params.put("email", email1);
params.put("password", password1);
response = webService.WebGet("getTables", params);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
C-->
public class ThirdActivity extends MyActivity {
String tablename1, row1, json1;
ArrayList<JSONStructure> arrayList = new ArrayList<JSONStructure>();
JSONArray jsonArray, jsonArray2;
JSONObject jsonObject;
String row;
String email1, password1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third_layout);
ListView listView = (ListView) findViewById(R.id.listview2);
TextView textView = (TextView) findViewById(R.id.title_textview);
Intent intent = getIntent();
tablename1 = intent.getExtras().getString("tablename");
row = intent.getExtras().getString("Rows");
textView.setText(tablename1);
json1 = intent.getExtras().getString("Json");
email1 = intent.getExtras().getString("email");
password1 = intent.getExtras().getString("password");
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
Button button = (Button) findViewById(R.id.goback);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ThirdActivity.this,
SecondActivity.class);
MyActivity.getActivityFromStack();
intent.putExtra("email", email1);
intent.putExtra("password", password1);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
ThirdActivity.this.startActivity(intent);
}
});
}
}.execute();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
final int position, long id) {
final ProgressDialog pd = ProgressDialog.show(
ThirdActivity.this, "Calling webservice...",
"Please wait...", true, false);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... paramArrayOfParams) {
pd.dismiss();
try {
jsonObject = new JSONObject(json1);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Intent intent = new Intent(ThirdActivity.this,
FinalActivity.class);
//MyActivity.addActivityToStack(ThirdActivity.this);
intent.putExtra("tablename", tablename1);
intent.putExtra("Json", jsonObject.toString());
intent.putExtra("Row", position);
intent.putExtra("email", email1);
intent.putExtra("password", password1);
ThirdActivity.this.startActivity(intent);
}
}.execute();
}
});
try {
JSONObject jsonObject = new JSONObject(json1);
JSONArray jsonArray = new JSONArray();
jsonArray = jsonObject.getJSONArray("FirstThree");
jsonArray2 = jsonObject.getJSONArray("Color");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String one = c.optString("One");
String two = c.optString("Two");
String three = c.optString("Three");
JSONObject c1 = jsonArray2.getJSONObject(i);
String color = c1.optString("color");
JSONStructure jsonStructure = new JSONStructure();
jsonStructure.column1 = one;
jsonStructure.column2 = two;
jsonStructure.column3 = three;
jsonStructure.setColumn1(one);
jsonStructure.setColumn2(two);
jsonStructure.setColumn3(three);
jsonStructure.setColor(color);
arrayList.add(jsonStructure);
Log.e("one", c.optString("One"));
Log.e("two", c.optString("Two"));
Log.e("three", c.optString("Three"));
Log.e("color", c1.optString("color"));
}
} catch (Exception e) {
e.printStackTrace();
}
if (arrayList != null && arrayList.size() > 0) {
MyAdapter1 adapter1 = new MyAdapter1(ThirdActivity.this, arrayList);
listView.setAdapter(adapter1);
}
Button btn = (Button) findViewById(R.id.logoutbutton);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog pd = ProgressDialog.show(
ThirdActivity.this, "Calling webservice...",
"Please wait...", true, false);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
pd.dismiss();
return null;
}
#Override
protected void onPostExecute(Void result) {
Intent intent = new Intent(ThirdActivity.this,
WebServiceActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
ThirdActivity.this.startActivity(intent);
super.onPostExecute(result);
}
}.execute();
}
});
}
}
Assuming you need this stack solely for the logout function, there are better ways. Use a broadcast instead. Register a BroadcastReceiver in MyActivity.onCreate. The receiver should just call the activity's finish(). Send the broadcast from the button's click listener (btn1? What does that button do? Couldn't guess from the name; better names required ;) ). That's it.

Categories

Resources