Android: how to get spinner value and check the condition - android

In my app i have a spinner with two items ..i have to choose the item an do action accordingly
dialogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String Comment = edittext.getText().toString();
String choose = spinner.getSelectedItem()
.toString();
if (Comment != null && Comment.equalsIgnoreCase("")){
post(Comment,choose);
getActivity().finish();
}else{
showToast("Please enter you comment!");
}
}
});
dialog.show();
dialog.getWindow().setAttributes(lp);
} catch (Exception e) {
e.printStackTrace();
getActivity().finish();
}
}
private void post(String comments, String choose) throws Exception{
StringBuffer finalMessage = new StringBuffer("\nRecomends " + Data.getfName());
if(Data.getAddress() != null && !Data.getAddress().isEmpty()){
finalMessage.append("\n" + Data.getAddress());
}
-----------------> if(spinner.getSelectedItem().toString().equals("Post to personal directory & FB")){
Bundle params = new Bundle();
params.putString("message",finalMessage.toString() );
publishStory(params,comments);
}else {
try {
new FBUtils(activity).sharePlaces(attractionData, comments, null);
} catch (Exception e) {
Log.e(TAG,"sharePlaces error ",e);
}
}
}
private void publishStory(Bundle postParams,final String comments,final String choose) {
Session session = Session.getActiveSession();
if (session != null){
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
}
Request.Callback callbackRequest= new Request.Callback() {
public void onCompleted(Response response) {
if (response == null || response.equals("")
|| response.equals("false")) {
showToast("Blank response.");
} else
new fbUtils(activity).share(Data, comments, response.getError(),choose);
} catch (Exception e) {
Log.e(TAG,"sharePlaces error ",e);
}
}
};
Request request = new Request(session, Constants.fb.fbId + "/comments", postParams,
HttpMethod.POST, callbackRequest);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
the issue is the post() is not executing when clicking the dailogbutton its going into else part, i want to execute the if condition in post() method, Any help is appreciated

As you are getting the value from the spinner. The value may not be updated one .
You should use item-selected listeners.
String result="";
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Toast.makeText(parent.getContext()), "The planet is " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
// Your variable should update here
result = parent.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
Now use that value in onPost method as:
private void post(String comments, String choose) throws Exception{
StringBuffer finalMessage = new StringBuffer("\nRecomends " + Data.getfName());
if(Data.getAddress() != null && !Data.getAddress().isEmpty()){
finalMessage.append("\n" + Data.getAddress());
}
Log.v("TEST",spinner.getSelectedItem().toString());
-----------------> if(result.equals("Post to personal directory & FB")){
Bundle params = new Bundle();
params.putString("message",finalMessage.toString() );
publishStory(params,comments);
}else {
try {
new FBUtils(activity).sharePlaces(attractionData, comments, null);
} catch (Exception e) {
Log.e(TAG,"sharePlaces error ",e);
}
}
}

Try like this:
private Spinner status;
status = (Spinner) findViewById(R.id.status);
final ArrayList<Simplestatus> statusList = new ArrayList<Simplestatus>();
Simplestatus tempstatus = new Simplestatus();
tempstatus.setSimpleStatusName("ZERO");
tempstatus.setSimpleStatusValue("0");
Simplestatus tempstatus1 = new Simplestatus();
tempstatus1.setSimpleStatusName("ONE");
tempstatus1.setSimpleStatusValue("1");
statusList.add(tempstatus);
statusList.add(tempstatus1);
SpinnerAdapter stateAdaptor = new SpinnerAdapter(SettingActivity.this,statusList);
// stateList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
status.setAdapter(stateAdaptor);
status.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
changeStatus(statusList.get(position));
selected = statusList.get(position).getsimpleStatusName();
System.out.println("selected"+selected);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
public class Simplestatus
{
private String simpleStatusName;
private String simpleStatusValue;
public String getSimpleStatusName()
{
return simpleStatusName;
}
public void setSimpleStatusName(String simpleStatusName)
{
this.simpleStatusName = simpleStatusName;
}
public String getsimpleStatusValue()
{
return simpleStatusValue;
}
public void setsimpleStatusValue(String simpleStatusValue)
{
this.simpleStatusValue = simpleStatusValue;
}
}

Related

Upload a file along with other string parameters in android

I have to upload a file and has three more parameters which is string.The file can be image or zip.How is it possible with volley to upload a file and submit string parameters along with it when button is clicked?
I have also tried this link-https://www.simplifiedcoding.net/upload-pdf-file-server-android/
Please help me.Thanks!!
My code is:
public class Tab1Fragment extends Fragment implements
AdapterView.OnItemSelectedListener {
EditText subj,desx;
private ImageView mAvatarImage;
Button choosefile,select,submt;
String uid, type;
String MY_PREFS_NAME = "value";
private int PICK_PDF_REQUEST = 1;
TextView filetext;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
String uploadId;
//Uri to store the image uri
private Uri filePath;
Spinner spinner,spinner2;
public Tab1Fragment() {
// Required empty public constructor
}
public static Tab1Fragment newInstance() {
Tab1Fragment fragment = new Tab1Fragment();
return fragment;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview= inflater.inflate(R.layout.fragment_tab1, container,
false);
subj=(EditText)rootview.findViewById(R.id.subj);
choosefile=(Button)rootview.findViewById(R.id.choosefile);
select=(Button)rootview.findViewById(R.id.select);
submt=(Button)rootview.findViewById(R.id.submt);
filetext=(TextView)rootview.findViewById(R.id.filetext);
mAvatarImage=(ImageView)rootview.findViewById(R.id.image);
desx=(EditText)rootview.findViewById(R.id.desx);
submt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveProfileAccount();
}
});
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showFileChooser();
}
});
choosefile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadMultipart();
}
});
requestStoragePermission();
SharedPreferences prefs =
this.getActivity().getSharedPreferences(MY_PREFS_NAME,
Context.MODE_PRIVATE);
uid = prefs.getString("uid", null);
spinner = (Spinner)rootview.findViewById(R.id.spinner);
spinner2 = (Spinner)rootview.findViewById(R.id.spinner2);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> deparment= new ArrayList<String>();
deparment.add("Support");
deparment.add("Project");
deparment.add("Payment");
deparment.add("Service");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item, deparment);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
List<String> priority= new ArrayList<String>();
priority.add("low");
priority.add("Medium");
priority.add("High");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item, priority);
// Drop down layout style - list view with radio button
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner2.setAdapter(dataAdapter2);
return rootview;
}
private void saveProfileAccount() {
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, Constants.UPLOAD_SUPPORT, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
String resultResponse = new String(response.data);
try {
JSONObject b = new JSONObject(resultResponse);
int status = b.getInt("status");
String data = b.getString("message");
Log.d("Response", data);
if (status ==100) {
/* Intent intent = new Intent(getActivity(),Skills.class);
startActivity(intent);*/
Toast.makeText(getActivity(), data, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String errorMessage = "Unknown error";
if (networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
errorMessage = "Request timeout";
} else if (error.getClass().equals(NoConnectionError.class)) {
errorMessage = "Failed to connect server";
}
} else {
String result = new String(networkResponse.data);
try {
JSONObject response = new JSONObject(result);
String status = response.getString("status");
String message = response.getString("message");
Log.e("Error Status", status);
Log.e("Error Message", message);
if (networkResponse.statusCode == 404) {
errorMessage = "Resource not found";
} else if (networkResponse.statusCode == 401) {
errorMessage = message+" Please login again";
} else if (networkResponse.statusCode == 400) {
errorMessage = message+ " Check your inputs";
} else if (networkResponse.statusCode == 500) {
errorMessage = message+" Something is getting wrong";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i("Error", errorMessage);
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("userid", uid);
params.put("department", spinner.getSelectedItem().toString());
params.put("priority",
spinner2.getSelectedItem().toString().trim());
params.put("subject", subj.getText().toString().trim());
params.put("description",desx.getText().toString().trim());
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// file name could found file base or direct access from real path
// for now just get bitmap data from ImageView
params.put("avatar", new DataPart("file_avatar.jpg", AppHelper.getFileDataFromDrawable(getContext(), mAvatarImage.getDrawable()), "*/*"));
return params;
}
};
VolleySingleton.getInstance(getContext()).addToRequestQueue(multipartRequest);
}
try this
public void fileUploadFunction() {
// Getting file path using Filepath class.
Pdfuri = FilePath.getPath(this, uri);
Log.d("Pdfuri", Pdfuri);
// If file path object is null then showing toast message to move file into internal storage.
if (Pdfuri == null) {
Toast.makeText(this, "Please move your PDF file to internal storage & try again.", Toast.LENGTH_LONG).show();
}
// If file path is not null then PDF uploading file process will starts.
else {
try {
PdfID = UUID.randomUUID().toString();
new MultipartUploadRequest(this, PdfID, AppConstants.URL)
.addFileToUpload(Pdfuri, "pdf")
.addParameter("course", course.trim())
.addParameter("course_id", c_id.trim())
.addParameter("stream", stream.trim())
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(5)
.startUpload();
Toast.makeText(MainActivity.this,"Successfully Uploaded",Toast.LENGTH_SHORT).show();
} catch (Exception exception) {
Toast.makeText(this,
exception.getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
//Read response here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
//Add post values here
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// Add you file here
return params;
}
};
VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
You can use multipart for this. Here is a sample code

How to wait for an activity to finish in asynctask

I know that the purpose of the AsyncTask is to run asynchronously with other tasks of the app and finish in the background, but apparently I need to do this, I need to start an activity from AsyncTask and since I cant extend an activity in this class I can not use startactivityforresult, so how can I wait till my activity finishes?
Here is my code:
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
public AsyncResponse delegate = null;
private static final String TAG = "ListSpdFiles: ";
Context applicationContext;
ContentResolver spdappliationcontext;
public final CountDownLatch setSignal= new CountDownLatch(1);
private final ReentrantLock lock = new ReentrantLock();
String username = "";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private boolean createbutt;
private boolean deletebutt;
private String initiator;
private String path;
private String pass;
private String url;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private String CurrentURL = null;
private PcasConnection pcasConnection = new PcasConnection() {
#Override
public void onPcasServiceConnected() {
Log.d(TAG, "pcasServiceConnected");
latch.countDown();
}
#Override
public void onPcasServiceDisconnected() {
Log.d(TAG, "pcasServiceDisconnected");
}
};
private CountDownLatch latch = new CountDownLatch(1);
public ListSpdFiles(boolean createbutt, boolean deletebutt, String url, String pass, Context context, String initiator, String path, AsyncResponse asyncResponse) {
this.initiator = initiator;
this.path = path;
this.pass= pass;
this.url= url;
this.createbutt= createbutt;
this.deletebutt=deletebutt;
applicationContext = context.getApplicationContext();
spdappliationcontext = context.getContentResolver();
delegate = asyncResponse;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(applicationContext, pcasConnection);
isConnected = pcas.connect();
}
private void term() {
Log.d(TAG, "terminating task");
if (pcas != null) {
pcas.disconnect();
pcas = null;
isConnected = false;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
init();
}
#Override
protected String[] doInBackground(Void... params) {
CurrentURL = getLastAccessedBrowserPage();
// check if connected to PCAS Service
if (!isConnected) {
Log.v(TAG, "not connected, terminating task");
return null;
}
// wait until connection with SPD is up
try {
if (!latch.await(20, TimeUnit.SECONDS)) {
Log.v(TAG, "unable to connected within allotted time, terminating task");
return null;
}
} catch (InterruptedException e) {
Log.v(TAG, "interrupted while waiting for connection in lsdir task");
return null;
}
// perform operation (this is where the actual operation is called)
try {
return lsdir();
} catch (DeadServiceException e) {
Log.i(TAG, "service boom", e);
return null;
} catch (DeadDeviceException e) {
Log.i(TAG, "device boom", e);
return null;
}
}
#Override
protected void onPostExecute(String[] listOfFiles) {
super.onPostExecute(listOfFiles);
if (listOfFiles == null) {
Log.i(TAG, "task concluded with null list of files");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
}
term();
delegate.processFinish(username);
}
#Override
protected void onCancelled(String[] listOfFiles) {
super.onCancelled(listOfFiles);
Log.i(TAG, "lsdir was canceled");
term();
}
/**
* Returns an array of strings containing the files available at the given path, or
* {#code null} on failure.
*/
private String[] lsdir() throws DeadDeviceException, DeadServiceException {
Result<List<String>> result = pcas.lsdir(initiator, path); // the lsdir call to the
boolean crtbut = createbutt;
boolean dlbut= deletebutt;
ArrayList<String> mylist = new ArrayList<String>();
final Global globalVariable = (Global) applicationContext;
if (crtbut==false && dlbut == false){
if ( globalVariable.getPasswordButt()==false ) {
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
Log.i(TAG, "current url: " + CurrentURL);
if (Arrays.toString(result.getValue().toArray(new String[0])).contains(CurrentURL)) {
String sharareh = Arrays.toString(result.getValue().toArray(new String[0]));
String[] items = sharareh.split(", ");
for (String item : items) {
String trimmed;
if (item.startsWith("[" + CurrentURL + ".")) {
trimmed = item.replace("[" + CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
} else if (item.startsWith(CurrentURL + ".")) {
trimmed = item.replace(CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
}
}
}
globalVariable.setPopupdone(false);
Intent i = new Intent(applicationContext, PopUp.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("EXTRA_SESSION_ID", mylist);
applicationContext.startActivity(i);
username = globalVariable.getUsername();
}
else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
//}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
public String getLastAccessedBrowserPage() {
String Domain = null;
Cursor webLinksCursor = spdappliationcontext.query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();
int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0)) {
webLinksCursor.moveToFirst();
while (webLinksCursor.isAfterLast() == false) {
if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1) {
if (!webLinksCursor.isNull(url_column_index)) {
Log.i("History", "Last page browsed " + webLinksCursor.getString(url_column_index));
try {
Domain = getDomainName(webLinksCursor.getString(url_column_index));
Log.i("Domain", "Last page browsed " + Domain);
return Domain;
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
webLinksCursor.moveToNext();
}
}
webLinksCursor.close();
return null;
}
public String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}}
My Activity class:
public class PopUp extends Activity {
private static final String TAG = "PopUp";
ArrayList<String> value = null;
ArrayList<String> usernames;
#Override
protected void onCreate(Bundle savedInstanceState) {
final Global globalVariable = (Global) getApplicationContext();
globalVariable.setUsername("");
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getStringArrayList("EXTRA_SESSION_ID");
}
usernames = value;
super.onCreate(savedInstanceState);
setContentView(R.layout.popupactivity);
final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button btnSelect = (Button) popupView.findViewById(R.id.select);
Spinner popupSpinner = (Spinner) popupView.findViewById(R.id.popupspinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PopUp.this, android.R.layout.simple_spinner_item, usernames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
popupSpinner.setAdapter(adapter);
popupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
globalVariable.setUsername(usernames.get(arg2));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnSelect.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
globalVariable.setPopupdone(true);
popupWindow.dismiss();
finish();
}
}
);
popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.poupup_menu, menu);
return true;
}}

List ImageView repeating same image when shared

I have a listView that is supposed to accept a shared message and image where the image is placed within the ImageView. This feature works for just the first message, but once an image is shared, each message received after that initial one becomes a copy of that same image even though the blank image placeholder was already set, which is just a one pixel black png:
holder.sharedSpecial.setImageResource(R.drawable.image_share_empty_holder);
An example is below:
The green textbox is the recipient. They have recieved a shared image from the yellow textbox. The yellow textbox then simply sends a normal message and I have set another image as a placeholder for normal messages: holder.sharedSpecial.setImageResource(R.drawable.image_share_empty_holder);
The same previously shared image takes precedence. I have used notifyDataSetChanged() so as to allow for the updating the adapter so that it would recognize not to use the same image, but to no avail.
How can I reformulate this class so that the image shared is only displayed with the proper message and not copied into each subsequent message?
The ArrayAdapter class:
public class DiscussArrayAdapter extends ArrayAdapter<OneComment> {
class ViewHolder {
TextView countryName;
ImageView sharedSpecial;
LinearLayout wrapper;
}
private TextView countryName;
private ImageView sharedSpecial;
private MapView locationMap;
private GoogleMap map;
private List<OneComment> countries = new ArrayList<OneComment>();
private LinearLayout wrapper;
private JSONObject resultObject;
private JSONObject imageObject;
String getSharedSpecialURL = null;
String getSharedSpecialWithLocationURL = null;
String specialsActionURL = "http://" + Global.getIpAddress()
+ ":3000/getSharedSpecial/";
String specialsLocationActionURL = "http://" + Global.getIpAddress()
+ ":3000/getSharedSpecialWithLocation/";
String JSON = ".json";
#Override
public void add(OneComment object) {
countries.add(object);
super.add(object);
}
public DiscussArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public int getCount() {
return this.countries.size();
}
private OneComment comment = null;
public OneComment getItem(int index) {
return this.countries.get(index);
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.message_list_item, parent, false);
holder = new ViewHolder();
holder.wrapper = (LinearLayout) row.findViewById(R.id.wrapper);
holder.countryName = (TextView) row.findViewById(R.id.comment);
holder.sharedSpecial = (ImageView) row.findViewById(R.id.sharedSpecial);
// Store the ViewHolder as a tag.
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
Log.v("COMMENTING","Comment is " + countries.get(position).comment);
//OneComment comment = getItem(position);
holder.countryName.setText(countries.get(position).comment);
// Initiating Volley
final RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
// Check if message has campaign or campaign/location attached
if (countries.get(position).campaign_id == "0" && countries.get(position).location_id == "0") {
holder.sharedSpecial.setImageResource(R.drawable.image_share_empty_holder);
Log.v("TESTING", "It is working");
} else if (countries.get(position).campaign_id != "0" && countries.get(position).location_id != "0") {
// If both were shared
getSharedSpecialWithLocationURL = specialsLocationActionURL + countries.get(position).campaign_id + "/" + countries.get(position).location_id + JSON;
// Test Campaign id = 41
// Location id = 104
// GET JSON data and parse
JsonObjectRequest getCampaignLocationData = new JsonObjectRequest(Request.Method.GET, getSharedSpecialWithLocationURL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
resultObject = response.getJSONObject("shared");
} catch (JSONException e) {
e.printStackTrace();
}
// Get and set image
Picasso.with(getContext()).load("http://" + Global.getIpAddress() + ":3000" + adImageURL).into(holder.sharedSpecial);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
requestQueue.add(getCampaignLocationData);
} else if (countries.get(position).campaign_id != "0" && countries.get(position).location_id == "0") {
// Just the campaign is shared
getSharedSpecialURL = specialsActionURL + countries.get(position).campaign_id + JSON;
// Test Campaign id = 41
// GET JSON data and parse
JsonObjectRequest getCampaignData = new JsonObjectRequest(Request.Method.GET, getSharedSpecialURL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
resultObject = response.getJSONObject("shared");
} catch (JSONException e) {
e.printStackTrace();
}
// Get and set image
Picasso.with(getContext()).load("http://" + Global.getIpAddress() + ":3000" + adImageURL).into(holder.sharedSpecial);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
requestQueue.add(getCampaignData);
// Location set to empty
}
// If left is true, then yellow, if not then set to green bubble
holder.countryName.setBackgroundResource(countries.get(position).left ? R.drawable.bubble_yellow : R.drawable.bubble_green);
holder.wrapper.setGravity(countries.get(position).left ? Gravity.LEFT : Gravity.RIGHT);
return row;
}
}
The messaging class that sends normal messages only but can receive image messages and set to the adapter:
public class GroupMessaging extends Activity {
private static final int MESSAGE_CANNOT_BE_SENT = 0;
public String username;
public String groupname;
private Button sendMessageButton;
private Manager imService;
private InfoOfGroup group = new InfoOfGroup();
private InfoOfGroupMessage groupMsg = new InfoOfGroupMessage();
private StorageManipulater localstoragehandler;
private Cursor dbCursor;
private com.example.feastapp.ChatBoxUi.DiscussArrayAdapter adapter;
private ListView lv;
private EditText editText1;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((MessagingService.IMBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(GroupMessaging.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.message_activity);
lv = (ListView) findViewById(R.id.listView1);
adapter = new DiscussArrayAdapter(getApplicationContext(), R.layout.message_list_item);
lv.setAdapter(adapter);
editText1 = (EditText) findViewById(R.id.editText1);
sendMessageButton = (Button) findViewById(R.id.sendMessageButton);
Bundle extras = this.getIntent().getExtras();
group.userName = extras.getString(InfoOfGroupMessage.FROM_USER);
group.groupName = extras.getString(InfoOfGroup.GROUPNAME);
group.groupId = extras.getString(InfoOfGroup.GROUPID);
String msg = extras.getString(InfoOfGroupMessage.GROUP_MESSAGE_TEXT);
setTitle("Group: " + group.groupName);
// Retrieve the information
localstoragehandler = new StorageManipulater(this);
dbCursor = localstoragehandler.groupGet(group.groupName);
if (dbCursor.getCount() > 0) {
// Probably where the magic happens, and keeps pulling the same
// thing
int noOfScorer = 0;
dbCursor.moveToFirst();
while ((!dbCursor.isAfterLast())
&& noOfScorer < dbCursor.getCount()) {
noOfScorer++;
}
}
localstoragehandler.close();
if (msg != null) {
// Then friends username and message, not equal to null, recieved
adapter.add(new OneComment(true, group.groupId + ": " + msg, "0", "0"));
adapter.notifyDataSetChanged();
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.cancel((group.groupId + msg).hashCode());
}
// The send button
sendMessageButton.setOnClickListener(new OnClickListener() {
CharSequence message;
Handler handler = new Handler();
public void onClick(View arg0) {
message = editText1.getText();
if (message.length() > 0) {
// When general texting, the campaign and location will always be "0"
// Only through specials sharing is the user permitted to change the campaign and location to another value
adapter.add(new OneComment(false, imService.getUsername() + ": " + message.toString(), "0", "0"));
adapter.notifyDataSetChanged();
localstoragehandler.groupInsert(imService.getUsername(), group.groupName,
group.groupId, message.toString(), "0", "0");
// as msg sent, will blank out the text box so can write in
// again
editText1.setText("");
Thread thread = new Thread() {
public void run() {
try {
// JUST PUTTING "0" AS A PLACEHOLDER FOR CAMPAIGN AND LOCATION
// IN FUTURE WILL ACTUALLY ALLOW USER TO SHARE CAMPAIGNS
if (imService.sendGroupMessage(group.groupId,
group.groupName, message.toString(), "0", "0") == null) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
R.string.message_cannot_be_sent,
Toast.LENGTH_LONG).show();
// showDialog(MESSAGE_CANNOT_BE_SENT);
}
});
}
} catch (UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(),
R.string.message_cannot_be_sent,
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
};
thread.start();
}
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
int message = -1;
switch (id) {
case MESSAGE_CANNOT_BE_SENT:
message = R.string.message_cannot_be_sent;
break;
}
if (message == -1) {
return null;
} else {
return new AlertDialog.Builder(GroupMessaging.this)
.setMessage(message)
.setPositiveButton(R.string.OK,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
/* User clicked OK so do some stuff */
}
}).create();
}
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(groupMessageReceiver);
unbindService(mConnection);
ControllerOfGroup.setActiveGroup(null);
}
#Override
protected void onResume() {
super.onResume();
bindService(new Intent(GroupMessaging.this, MessagingService.class),
mConnection, Context.BIND_AUTO_CREATE);
IntentFilter i = new IntentFilter();
i.addAction(MessagingService.TAKE_GROUP_MESSAGE);
registerReceiver(groupMessageReceiver, i);
ControllerOfGroup.setActiveGroup(group.groupName);
}
// For receiving messages form other users...
public class GroupMessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extra = intent.getExtras();
//Log.i("GroupMessaging Receiver ", "received group message");
String username = extra.getString(InfoOfGroupMessage.FROM_USER);
String groupRId = extra.getString(InfoOfGroupMessage.TO_GROUP_ID);
String message = extra
.getString(InfoOfGroupMessage.GROUP_MESSAGE_TEXT);
// NEED TO PLACE INTO THE MESSAGE VIEW!!
String received_campaign_id = extra.getString(InfoOfGroupMessage.CAMPAIGN_SHARED);
String received_location_id = extra.getString(InfoOfGroupMessage.LOCATION_SHARED);
// NEED TO INTEGRATE THIS INTO LOGIC ABOVE, SO IT MAKES SENSE
if (username != null && message != null) {
if (group.groupId.equals(groupRId)) {
adapter.add(new OneComment(true, username + ": " + message, received_campaign_id, received_location_id));
localstoragehandler
.groupInsert(username, groupname, groupRId, message, received_campaign_id, received_location_id);
Toast.makeText(getApplicationContext(), "received_campaign: " + received_campaign_id +
" received_location:" + received_location_id, Toast.LENGTH_LONG).show();
received_campaign_id = "0";
received_location_id = "0";
} else {
if (message.length() > 15) {
message = message.substring(0, 15);
}
Toast.makeText(GroupMessaging.this,
username + " says '" + message + "'",
Toast.LENGTH_SHORT).show();
}
}
}
}
;
// Build receiver object to accept messages
public GroupMessageReceiver groupMessageReceiver = new GroupMessageReceiver();
#Override
protected void onDestroy() {
super.onDestroy();
if (localstoragehandler != null) {
localstoragehandler.close();
}
if (dbCursor != null) {
dbCursor.close();
}
}
}
I have gone through your code and this is common problem with listview that images starts repeating itself. In your case I think you have assigned image to Imageview every if and else if condition but if none of the condition satisfy it uses the previous image.
I would suggest to debug the getview method and put break points on the setImageResource. I use volley for these image loading and it has a method called defaultImage so that if no url is there the image is going to get the default one. So add that default case and see if it works.
If any of the above point is not clear feel free to comment.

Android TextView doesn't update

I am developing an Android app. Please see the Java code below. Can you please explain why textView doesn't update at specific lines in code but updates at others. I have them commented in the code.
I have updated the code see below.
The idea is to get a facebook profile from a server. When profiling_status equals 2 means that the profile is not ready, so I'll just ping the server until I get profiling_status != 2..
I tried the progress dialog thingy but gave up cause I put my activity in a thread, but then I couldn't get some information because I should have run it in nonUIThread.. Tried that but I failed and I lost patience.. so decided that while I ping the server I should just print "Loading profile. Please wait." No mess, no fuss! Only as said, textView doesn't update. Interestingly enough.. System.out.println("Here"); gets executed. I am running it only on AVD at the moment cause the server is not on the wireless network so I can't use a mobile phone to test it.
public class SelectionFragment extends Fragment {
private ProfilePictureView profilePictureView;
private TextView userNameView;
private UiLifecycleHelper uiHelper;
private static final int REAUTH_ACTIVITY_CODE = 100;
private TextView textView;
private String username = null;
Context context;
JSONObject json = null;
JSONObject json_facebook = null;
int time = 0;
int time_interval = 3000;
int profiling_status = 2;
String logincode;
String usermessage = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REAUTH_ACTIVITY_CODE) {
uiHelper.onActivityResult(requestCode, resultCode, data);
}
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(final Session session, final SessionState state, final Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void deleteProfile() throws JSONException {
IDThiefHTTPRequest.deleteProfile();
textView.setTextColor(Color.GRAY);
textView.setGravity(Gravity.CENTER);
textView.setText("Press Get profile info button to process your risk of identity theft");
//Facebook logout
Session session2 = Session.getActiveSession();
if (session2 != null) {
session2.close();
}
else {
session2 = new Session(context);
Session.setActiveSession(session2);
session2.close();
}
}
private String readRiskScoreArray(JSONArray json_riskscore) throws NumberFormatException, JSONException{
//get the risk score with only two digits
double risk_score = Double.valueOf(json_riskscore.get(0).toString());
String risk_score2digits = new DecimalFormat("##.##").format(risk_score);
String usermessage = "Your risk score is: ";
usermessage = usermessage + risk_score2digits;
usermessage = usermessage + " which is ranked as: ";
usermessage = usermessage + json_riskscore.get(2).toString();
JSONArray json_reasons = json_riskscore.getJSONArray(1);
for (int i = 0; i < json_reasons.length(); i++){
JSONArray json_reason = json_reasons.getJSONArray(i);
JSONArray json_reasondetails = json_reason.getJSONArray(1);
usermessage = usermessage + "\n\nReason: ";
usermessage = usermessage + json_reasondetails.get(0);
usermessage = usermessage + "\n\nIDThief suggests you to: ";
usermessage = usermessage + json_reasondetails.get(1);
usermessage = usermessage + "\n\nFix it through this link:\n";
usermessage = usermessage + json_reasondetails.get(2);
}
return usermessage;
}
private void displayProfileInfo() throws JSONException {
Session session = Session.getActiveSession();
if (session.isOpened()) {
System.out.println(session.getAccessToken());
}
if (username != null) {
System.out.println("Login stage: Getting profile info for user:" + username);
logincode = username + "!" + session.getAccessToken();
json = IDThiefHTTPRequest.makeLoginHTTPRequest(logincode);
System.out.println(json.toString(4));
json_facebook = json.getJSONObject("facebook");
//profiling_status
profiling_status = Integer.valueOf(json_facebook.get("profiling_status").toString());
if (profiling_status == 2) {
try {
while (profiling_status == 2 && time < 100000) {
textView.setTextColor(Color.BLACK);
textView.setGravity(Gravity.NO_GRAVITY);
textView.setText("Loading profile. Please wait.");
System.out.println("Here");
try {
Thread.sleep(time_interval);
time += time_interval;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
json = IDThiefHTTPRequest.makeLoginHTTPRequest(logincode);
json_facebook = json.getJSONObject("facebook");
//profiling_status
profiling_status = Integer.valueOf(json_facebook.get("profiling_status").toString());
}
if (time >= 100000) {
System.out.println("Time is out");
textView.setText("Server is not responding. Please try again later.");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
JSONArray json_riskscore = json_facebook.getJSONArray("risk_score");
System.out.println(json_riskscore.toString(4));
usermessage = readRiskScoreArray(json_riskscore);
textView.setTextColor(Color.BLACK);
textView.setGravity(Gravity.NO_GRAVITY);
textView.setText(usermessage);
}
else System.out.println("username is null");
}
#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.selection,
container, false);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Button deletebutton = (Button) view.findViewById(R.id.ImageButton2);
deletebutton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try {
deleteProfile();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Button button = (Button) view.findViewById(R.id.ImageButton1);
textView = (TextView) view.findViewById(R.id.profiletext);
textView.setMovementMethod(new ScrollingMovementMethod());
textView.setMovementMethod(LinkMovementMethod.getInstance());
button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try {
displayProfileInfo();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// Find the user's profile picture custom view
profilePictureView = (ProfilePictureView) view.findViewById(R.id.selection_profile_pic);
profilePictureView.setCropped(true);
// Find the user's name view
userNameView = (TextView) view.findViewById(R.id.selection_user_name);
// Check for an open session
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// Get the user's data
makeMeRequest(session);
}
return view;
}
private void makeMeRequest(final Session session) {
// Make an API call to get user data and define a
// new callback to handle the response.
Request request = Request.newMeRequest(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
if (session == Session.getActiveSession()) {
if (user != null) {
// Set the id for the ProfilePictureView
// view that in turn displays the profile picture.
profilePictureView.setProfileId(user.getId());
// Set the Textview's text to the user's name.
userNameView.setText(user.getName());
username = user.getUsername();
//System.out.println("Log in=====================================");
}
}
if (response.getError() != null) {
// Handle errors, will do so later.
}
}
});
request.executeAsync();
}
private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
if (session != null && session.isOpened()) {
// Get the user's data.
makeMeRequest(session);
}
else if (session != null && session.isClosed()) {
textView.setTextColor(Color.GRAY);
textView.setGravity(Gravity.CENTER);
textView.setText("Press Get profile info button to process your risk of identity theft");
}
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
uiHelper.onSaveInstanceState(bundle);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
}
I thing your username is a string . Normally it will be so use !username.equals() dont use != in string comparison. that code may not get executed
if (username != null || !username.equals("")) {
//to do
}
Try out as below to compare the string do not use == use equalsIgnoreCase() or equals() method.
if (profiling_status.equalsIgnoreCase("2")) {
//would not update here either
try {
while (profiling_status.equalsIgnoreCase("2") && time < 100000) {
textView.setText("Loading profile. Please wait.");
try {
Thread.sleep(time_interval);
time += time_interval;
} catch (InterruptedException e) {
e.printStackTrace();
}

Android Dialog box with remote server login

Here is a little initialization of the AlertDialog in Android and a method to verify a user using HttpClient
private void loginBox() {
USERS = db.getUserData();
login_layout = (LinearLayout) findViewById(R.id.loginlayout);
loginLayout = (LinearLayout) View.inflate(this, R.layout.login, null);
usernameEditText = (EditText) loginLayout.findViewById(R.id.username);
passwordEditText = (EditText) loginLayout.findViewById(R.id.password);
rememmber = (CheckBox) loginLayout.findViewById(R.id.checkBox1);
gallery = (Gallery) loginLayout.findViewById(R.id.users_gallery);
notificationText = (TextView) loginLayout
.findViewById(R.id.notificationtext);
userChooseText = (TextView) loginLayout
.findViewById(R.id.user_choose_text);
breakLine = (View) loginLayout.findViewById(R.id.login_break_line);
registerForContextMenu(loginLayout);
galleryVisibility();
gallery.setAdapter(new AddImgAdp(this));
if (userPrefs.getUserName() == null
&& userPrefs.getUserPassword() == null) {
if (!USERS.isEmpty()) {
System.out.println("not empty");
usernameEditText.setText(
USERS.get(gallery.getSelectedItemPosition())
.getUsername(), TextView.BufferType.EDITABLE);
passwordEditText.setText(
USERS.get(gallery.getSelectedItemPosition())
.getPassword(), TextView.BufferType.EDITABLE);
}
}
gallery.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
selectedUser = USERS.get(arg2).getUsername();
if (!USERS.isEmpty()) {
System.out.println("not empty");
usernameEditText.setText(USERS.get(arg2).getUsername(),
TextView.BufferType.EDITABLE);
passwordEditText.setText(USERS.get(arg2).getPassword(),
TextView.BufferType.EDITABLE);
}
return false;
}
});
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
usernameEditText.setText(USERS.get(position).getUsername(),
TextView.BufferType.EDITABLE);
passwordEditText.setText(USERS.get(position).getPassword(),
TextView.BufferType.EDITABLE);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// rememmber.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v) {
// if (rememmber.isChecked()) {
// Toast toast = Toast.makeText(getApplicationContext(),
// "Try to avoid this option, it is unsecure!",
// Toast.LENGTH_LONG);
// toast.show();
//
// // TODO: store in DB
// }
// }
// });
Button loginButton = (Button) loginLayout
.findViewById(R.id.action_login);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
username = usernameEditText.getText().toString();
password = passwordEditText.getText().toString();
if (rememmber.isChecked()) {
db.createNewUser(username, password);
}
if (testUser()) {
// gallery.removeAllViewsInLayout();
username = usernameEditText.getText().toString();
password = passwordEditText.getText().toString();
userPrefs.savePrefs(username, password);
alert.dismiss();
// alert.cancel();
// login = null;
// alert = null;
} else {
userPrefs.clearPrefs();
System.out.println("Gallery children: "
+ gallery.getChildCount());
notificationText.setText("Username or password incorrect!");
notificationText.setTextColor(Color.RED);
USERS = db.getUserData();
galleryVisibility();
((BaseAdapter) gallery.getAdapter()).notifyDataSetChanged();
gallery.setSelection(gallery.getCount());
}
}
});
if (!initialized) {
System.out.println("Run login box initialization");
initialized = true;
login = new AlertDialog.Builder(this);
login.setView(loginLayout).setTitle("Logon Credentials")
.setCancelable(false);
alert = login.create();
alert.show();
}
}
private void galleryVisibility() {
if (USERS.size() < 1) {
gallery.setEnabled(false);
gallery.setVisibility(LinearLayout.INVISIBLE);
breakLine.setEnabled(false);
breakLine.setVisibility(LinearLayout.INVISIBLE);
userChooseText.setEnabled(false);
userChooseText.setVisibility(LinearLayout.INVISIBLE);
} else {
gallery.setEnabled(true);
gallery.setVisibility(LinearLayout.VISIBLE);
breakLine.setEnabled(true);
breakLine.setVisibility(LinearLayout.VISIBLE);
userChooseText.setEnabled(true);
userChooseText.setVisibility(LinearLayout.VISIBLE);
}
}
private boolean testUser() {
System.out.println("Testing user");
if (usernameEditText.getText().toString()!= null
&& , passwordEditText.getText().toString() != null) {
try {
System.out.println("getting viewwstate");
String viewState = client
.httpGetViewstate("http://website/Login.aspx");
HttpResponse response = client.httpPost1(viewState,
"http://website/Login.aspx",
usernameEditText.getText().toString(), passwordEditText
.getText().toString());
System.out.println("posted!");
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
System.out.println(responseText);
// String commentsHtml = client
// .httpGet("http://website/PriceTables.aspx");
// System.out.println(commentsHtml);
if (responseText.contains("Log Out")) {
success = true;
System.out.println("username is ok");
this.finish();
return true;
} else {
System.out.println("back again..");
fail = true;
// loginBox();
return false;
}
} catch (SocketTimeoutException socket) {
System.out.println("login socket timeout");
} catch (IOException e) {
System.out.println("Login io exception");
}
return false;
} else {
// Intent login = new Intent(getApplicationContext(),
// Login.class);
// startActivity(login);
fail = true;
// loginBox();
return false;
}
}
The problem is that when I click login button for the first time, everything works fine, but when I click it the second time, the testUserMethod, try{ statement is ignored.. Found the problem - again, my own mistake, everything is ok now. Thank you everybody who helped
Can you check with setCancelable().. you are setting it to true once and again to false...
It looks like problem isn't here. Maybe, you did some field static?

Categories

Resources