App getting error while trying to report error - java

so I'm using the androidhive tutorial to make a server for my app and connect to it. I have it so the server will send back different messages depending on what was sent in but I'm getting an error with it and I can't figure out why. Here is the class that the error occurs in:
class CreateNewSpot extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewSpotActivity.this);
pDialog.setMessage("Creating Spot..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String longitude = inputLong;
String latitude = inputLat;
String pavement = spinner_pavement.getSelectedItem().toString();
String traffic = spinner_traffic.getSelectedItem().toString();
String environment = spinner_enviro.getSelectedItem().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("longitude", longitude));
params.add(new BasicNameValuePair("latitude", latitude));
params.add(new BasicNameValuePair("pavement", pavement));
params.add(new BasicNameValuePair("traffic", traffic));
params.add(new BasicNameValuePair("environment", environment));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
switch(success){
case 0:
//name is empty!
break;
case 1:
// successfully created product
Intent i = new Intent(getApplicationContext(),
AllSpotsActivity.class);
startActivity(i);
// closing this screen
finish();
break;
case 2:
//name has been taken
Toast.makeText(getApplicationContext(), "Name for spot has already been taken.", Toast.LENGTH_LONG).show();
break;
case 3:
//server error
Toast.makeText(getApplicationContext(), "A server error has occurred.", Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(getApplicationContext(), "An unknown error has occurred.", Toast.LENGTH_LONG).show();
//just an unknown error
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
Now I'm purposely sending in data to get success==2 but it tells me my app unexpected error has occurred. Why is this? Is it because of the pDialog is still open? I tried putting pDialog.dismiss(); above but I still get the error. Sorry if this is a simple question and thank you in advance.
Tyler
EDIT:
Logcat:
class CreateNewSpot extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewSpotActivity.this);
pDialog.setMessage("Creating Spot..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String longitude = inputLong;
String latitude = inputLat;
String pavement = spinner_pavement.getSelectedItem().toString();
String traffic = spinner_traffic.getSelectedItem().toString();
String environment = spinner_enviro.getSelectedItem().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("longitude", longitude));
params.add(new BasicNameValuePair("latitude", latitude));
params.add(new BasicNameValuePair("pavement", pavement));
params.add(new BasicNameValuePair("traffic", traffic));
params.add(new BasicNameValuePair("environment", environment));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
switch(success){
case 0:
//name is empty!
break;
case 1:
// successfully created product
Intent i = new Intent(getApplicationContext(),
AllSpotsActivity.class);
startActivity(i);
// closing this screen
finish();
break;
case 2:
//name has been taken
error_msg = 0;
break;
case 3:
//server error
error_msg = 1;
break;
default:
error_msg = 2;
//just an unknown error
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
switch(error_msg){
case 0:
Toast.makeText(getApplicationContext(), "Name for spot has already been taken.", Toast.LENGTH_LONG).show();
break;
case 1:
Toast.makeText(getApplicationContext(), "A server error has occurred.", Toast.LENGTH_LONG).show();
break;
case 2:
Toast.makeText(getApplicationContext(), "An unknown error has occurred.", Toast.LENGTH_LONG).show();
break;
default:
break;
}
pDialog.dismiss();
}
}

You are getting unexpected error because you are showing Toast from doInBackground(), which you can't do. You never handle your UI from background in AsyncTask. Just remove your try-catch block from doInBackground() to onPostExecute() and it will work.

Related

Android Eclipse 'Source not found' at execute

I've a problem in Eclipse while coding an Android App..
If I'm in debug mode and go line-by-line through my code I get an error with the Message "Source not found".
Here is my Code:
public boolean checkVersion(){
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://"+this.ip+"/fastorder/android/checkDatabaseVersion.php"); // make sure the url is correct.
try{
String db_vers = String.valueOf(DATABASE_VERSION);
//add your data
nameValuePairs = new ArrayList<NameValuePair>();
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("version", db_vers)); // $Edittext_value = $_POST['Edittext_value'];
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
//response = httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response: " + response);
if(response.equalsIgnoreCase("true")){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle("Speisekarte aktualisieren?");
// set dialog message
alertDialogBuilder
.setMessage("Wollen Sie jetzt die aktuelle Version der Speisekarte downloaden?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
loadUpdate();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
else if(response.equalsIgnoreCase("false")){
}
}catch(ClientProtocolException e){
Log.e("FastOrder", "Exception : " + e);
}catch(IOException e){
Log.e("FastOrder", "Exception : " + e);
}
return true;
}
the error apears in: String response = httpclient.execute(httppost, responseHandler); line...
Anyone has an answer? I try to fix this since days...
This happens because the source code for the method you are trying to access cannot be found.
Try pressing [F6] at the line where you get the error.

Toast for invalid login not showing? Android

I'm making a login app with android. I'm trying to show a dialog that shows up whenever I enter an invalid credentials but it's not working? what Am i doing wrong?
I am able to log in fine though I just need the error toast
Code snippet
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this, "",
"Validating your Account", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.3.2/sunshine-ems/login.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("username",inputUsername.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password",inputPassword.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
String username = inputUsername.getText().toString().trim();
switch(Integer.parseInt(response)){
case 0:
session.createLoginSession(username);
Intent b = new Intent(MainActivity.this, Profile.class);
startActivity(b);
finish();
break;
default:
Toast.makeText(MainActivity.this,"Invalid username or password.", Toast.LENGTH_LONG).show();
break;
}
dialog.dismiss();
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
}
Logcat for invalid input
01-01 14:16:37.179: W/audio_hw_primary(111): out_write() limiting sleep time 32244 to 23219
01-01 14:16:47.699: W/audio_hw_primary(111): out_write() limiting sleep time 44149 to 23219
01-01 14:16:47.711: W/SingleClientConnManager(1571): Invalid use of SingleClientConnManager: connection still allocated.
01-01 14:16:47.711: W/SingleClientConnManager(1571): Make sure to release the connection before allocating another one.
01-01 14:16:47.723: W/EGL_emulation(1571): eglSurfaceAttrib not implemented
01-01 14:16:47.723: W/audio_hw_primary(111): out_write() limiting sleep time 55759 to 23219
01-01 14:16:47.747: I/System.out(1571): Exception : Invalid int: ""
01-01 14:16:47.755: W/audio_hw_primary(111): out_write() limiting sleep time 27369 to 23219
01-01 14:16:47.927: W/InputMethodManagerService(472): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#53241ec4 attribute=null, token = android.os.BinderProxy#533337e4
01-01 14:16:47.931: W/audio_hw_primary(111): out_write() limiting sleep time 25917 to 23219
You are trying to update UI from a background thread.It is not possible.
Use AsyncTask . Check login details in doInBackground(). Show the Toast/AlertDialogue in onPostExecute().
Here is a nice example to learn the usage of AsyncTask
add this to you activity
private class Login extends AsyncTask<Void,Void,Void>{
private int result=9;
#Override
protected Void doInBackground(Void... params) {
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.3.2/sunshine-ems/login.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("username",inputUsername.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password",inputPassword.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
result=Integer.parseInt(response);
return null;
}catch (Exception e){
System.out.println("Exception : " + e.getMessage());
return null;
}
}
#Override
protected onPostExecute(){
switch(Integer.parseInt(response)){
case 0:
session.createLoginSession(username);
Intent b = new Intent(MainActivity.this, Profile.class);
startActivity(b);
finish();
break;
default:
Toast.makeText(MainActivity.this,"Invalid username or password.", Toast.LENGTH_LONG).show();
break;
}
}
}
and this to you onResume or onCreate
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this, "",
"Validating your Account", true);
new Login().execute()
}
});
and read about the AsyncTask in Official docs and a tutorial.

Error parsing dataorg.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

I work in a android app which should show the details of a virtual database(WAMPSERVER i use) and make new documents. When i push the button of show details the app displays the above error.The following is the allproductsactivity.java file.I have see and other similar post but i can't understand and solve my problem. I put x.x.x.x:80 on IP address for security reasons.
AllProductsActivity.java
package com.panos.appphpconnect;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class AllProductsActivity extends ListActivity {
private ProgressDialog pDialog;
JSONParser jParser=new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://x.x.x.x:80/connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CLASSES = "classes";
private static final String TAG_PID = "_id";
private static final String TAG_NAME = "username";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.allproducts);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String _id = ((ListView) view.findViewById(R.id.id)).getAdapter().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, _id);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(pDialog!=null && pDialog.isShowing()){
pDialog.cancel();
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON response
Log.d("All products:",json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_CLASSES);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.id, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
The code of get_all_products.php is the following
<?php
/*
* Following code will list all the products
*/
// array for json response
$response = array();
// include db connect class
require("db_connect.php");
// connecting to db
$db = new DB_CONNECT();
// get all products from classes table
$result = mysql_query("SELECT *FROM classes") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result)>0) {
// looping through all results
// products node
$response["classes"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$classes = array();
$classes["_id"] = $row["_id"];
$classes["username"] = $row["username"];
$classes["password"] = $row["password"];
// push single product into final response array
array_push($response["classes"], $classes);
}
// success
$response["success"] = 1;
// echoing panos response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No submissions found";
// echo no users json
echo json_encode($response);
}
?>
Also when i run the file get_all_products.php on my browser displays me the error " Parse error: syntax error, unexpected T_STRING, expecting T_FUNCTION in C:\wamp\www\connect\db_connect.php on line 6" but i don't understand which is line 6 and what is the error.The code of db_connect.php file is the below.
<?php
//A class file to connect to database
class DB_CONNECT{
function_constructor(){
$db = new DB_CONNECT();
//connecting to database
$this->connect();
}
function_destruct(){
//closing db connection
$this->close();
}
//Function to connect with database
function connect(){
//import database connection variables
require_once_DIR_ . '/db_config.php';
//connecting to mysql db
$con=mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD) or die(mysql_error());
//selecting database
$db=mysql_select_db(DB_DATABASE) or die(mysql_error());
//returning connrction cursor
return $con;
}
//function close to db connection
function close(){
//closing db connection
mysql_close();
}
}
?>
That's all errors of logocat
E/JSON Parser(2234): Error parsing dataorg.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
W/dalvikvm(2234): threadid=10: thread exiting with uncaught exception (group=0xb4e1e908)
E/AndroidRuntime(2234): FATAL EXCEPTION: AsyncTask #1
E/AndroidRuntime(2234): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime(2234): at android.os.AsyncTask$3.done(AsyncTask.java:299)
E/AndroidRuntime(2234): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
E/AndroidRuntime(2234): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
E/AndroidRuntime(2234): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
E/AndroidRuntime(2234): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
E/AndroidRuntime(2234): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
E/AndroidRuntime(2234): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
E/AndroidRuntime(2234): at java.lang.Thread.run(Thread.java:856)
E/AndroidRuntime(2234): Caused by: java.lang.NullPointerException
E/AndroidRuntime(2234): at com.panos.appphpconnect.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:141)
E/AndroidRuntime(2234): at com.panos.appphpconnect.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1)
E/AndroidRuntime(2234): at android.os.AsyncTask$2.call(AsyncTask.java:287)
E/AndroidRuntime(2234): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
E/AndroidRuntime(2234): ... 4 more
SELECT *FROM classes is invalid syntax and when you query you should pass the connection to mysql_query
$result = mysql_query("SELECT * FROM classes", $db) or die(mysql_error());
And forget about android now, get this to work in your browser then you can worry about parsing it in your app.

Accessing username from all classes: Android

Background Information:
I am developing a small application. The way it works right now is the moment the app is launched, the user is prompted with the main activity. Then from there, the user clicks on the login button which prompts the login activity. Now in my login activity, I have set an Intent that gets the user's username and then stores it in the Shared Preferences. If the login is successful then the user goes to the mainloggedinpage where the user sees: [Welcome back {username}]
The problem is the following:
If the user is accessing the mainloggedinpage via loginactivity then you can easily see his username which is exactly what I want. But the thing is that on the main page, I have other buttons which goes to other activities. The moment the user click on any of those activities and then returns to the mainloggedin page, then all you see is: [Welcome Back {}]. His username is not displayed anymore.
My question:
Can anyone suggest a quick fix that will allow me to display the username so even when the user goes to another activity from the mainloggedinpage and then comes back to the mainloggedinpage, the user will still see: [Welcome Back {username}]?
My Code for Login Activity [This is where I am getting the username]:
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
// save user data
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = sp.edit();
edit.putString("username", username);
edit.commit();
Intent i = new Intent(Login.this, mainpage.class);
i.putExtra("Welcome back, username", username);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
My Code for mainloggedinActivity [This is where the username is displayed]:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mainpage);
msuggestions = (Button) findViewById(R.id.btn_suggestions);
msuggestions.setOnClickListener(this);
mprayertimes = (Button)findViewById(R.id.btn_activityone);
mprayertimes.setOnClickListener(this);
mqibladirection =(Button)findViewById(R.id.btn_activitytwo);
mqibladirection.setOnClickListener(this);
mnewsboard = (Button) findViewById(R.id.newsboard);
mnewsboard.setOnClickListener(this);
mhadiths = (Button) findViewById(R.id.btn_activitythree);
mhadiths.setOnClickListener(this);
mchat = (Button) findViewById(R.id.btn_discussion);
mchat.setOnClickListener(this);
mallahnames = (Button) findViewById(R.id.btn_activityfour);
mallahnames.setOnClickListener(this);
// Get Username Start
TextView txt_loggedName = (TextView) findViewById(R.id.txt_loggedName);
Intent intent = getIntent();
String username = intent.getStringExtra("Welcome back, username");
txt_loggedName.setText(username);
// Get Username End
buttonLogout = (Button) findViewById(R.id.logout);
buttonLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
SharedPreferences.Editor editor=mPreferences.edit();
editor.remove("username");
editor.remove("password");
editor.commit();
Message myMessage=new Message();
myMessage.obj="NOTSUCCESS";
handler.sendMessage(myMessage);
finish();
}
});
Can anyone help me out so then when a user goes to the mainpage and click on one of the button and then comes back to the mainpage, it still displays his username? :)
Don't rely on an Intent extra for storing the username, since that will only be populated directly after the user logs in.
Replace this:
Intent intent = getIntent();
String username = intent.getStringExtra("Welcome back, username");
txt_loggedName.setText(username);
With:
String username = PreferenceManager.getDefaultSharedPreferences(this).getString("username", "guest");
txt_loggedName.setText("Welcome back, " + username);
Instead of getting the username from the intent, You should get it from the SharedPreferences since you already saved it there.

Updating mySQL database

When updating values into database, instead of updating 1 row each time(which is what we wanted), it update the whole database column.
Here are my codes:
Java code:
private Dialog alertDialog() { final AlertDialog.Builder
alertDialog = new AlertDialog.Builder(NotificationActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Confirmation...");
// Setting Dialog Message
alertDialog.setMessage("Do you want to accept this job?");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.ic_dialog_alert);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "Accept", Toast.LENGTH_SHORT).show();
// Return Result from alertdialog to database
result = "accepted";
System.out.println("The result is "+ result);
new UpdateActivity().execute();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "Reject", Toast.LENGTH_SHORT).show();
dialog.cancel();
// Return Result from alertdialog to database
result = "rejected";
System.out.println("The result is "+ result);
new UpdateActivity().execute();
}
});
return alertDialog.show(); }
/** * Background Async Task to update database * */ class
UpdateActivity extends AsyncTask {
/** * Before starting background thread Show Progress Dialog * */
#Override protected void onPreExecute() { super.onPreExecute();
pDialog = new ProgressDialog(NotificationActivity.this);
pDialog.setMessage("Sending ...");
pDialog.setIndeterminate(false); pDialog.setCancelable(true);
pDialog.show(); }
/** * Saving product * */ protected String
doInBackground(String... args) {
System.out.println("Sending...");
// getting updated data from dialog String confirmation =
result.toString();
System.out.println("Result to string..." + confirmation );
// Building Parameters List<NameValuePair> params = new
ArrayList(); params.add(new BasicNameValuePair(TAG_ID,
uid)); params.add(new BasicNameValuePair(TAG_RESULT, confirmation));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(UPDATE_URL,
"POST", params);
System.out.println("Json parsing...");
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
System.out.println("Checking...");
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), JobsAcceptedActivity.class);
startActivity(i);
//Toast.makeText(getApplicationContext(), "Update successfully...", Toast.LENGTH_SHORT).show();
System.out.println("Successfully updated...");
// closing this screen
finish();
} else {
// failed to create product
//Toast.makeText(getApplicationContext(), "Update unsucessfully...", Toast.LENGTH_SHORT).show();
System.out.println("Update unsuccessfully...");
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Done!");
return null; }
/**
* After completing background task Dismiss the progress dialog
* **/ protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss(); }
} }
PHP code:
$response = array(); // check for required fields if
(isset($_POST['UID']) && isset($_POST['accept'])) {
$UID = $_POST['UID'];
$accept = $_POST['accept'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql update row with matched pid
$result = mysql_query("UPDATE notification SET accept = '$accept' WHERE UID = $UID");
// check if column inserted or not
if ($result) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Notification successfully updated.";
// echoing JSON response
echo json_encode($response);
} else {
} } else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
Q: When updating values into database, instead of updating 1 row each time(which is what we wanted), it update the whole database column.
A: It sounds like you probably want a more restrictive "where" clause on your update :)
This is your one ==> $result = mysql_query("UPDATE notification SET accept = '$accept' WHERE UID = $UID");
My Suggession ==> $result = mysql_query("UPDATE notification SET accept = '$accept' WHERE UID = '$UID'"); or
$queryString= "UPDATE notification SET accept = ".$accept." WHERE UID =".$UID;
$result = mysql_query($queryString);

Categories

Resources