кнопка переключения с функцией обновления mysql

Я программирую приложение, в котором пользователь может переключить переключатель в положение «Ja» (англ. Yes) и «Nein» (англ. No), чтобы начать действие (Training / Spiel). Макет работает нормально, положение переключателя сохраняется при выходе из активности или приложения.

Но как я могу реализовать MySQL обновление базы данных, если переключатель установлен на «Ja» или «Nein»? Если switchSpiel расположен на «Ja», я хочу выполнить

UPDATE users SET spiel_anmel = '$training' WHERE firstname ='$name'

Есть идеи? Спасибо заранее.

public class Abmeldung extends Activity {
Button zurueck;
private TextView textViewSpiel;
private TextView textViewTraining;
private Switch switchSpiel;
private Switch switchTraining;
String firstname;
String spiel_anmel;
String spiel_anmel1;
InputStream is = null;
String result = null;
String line = null;
int code;
private String urlt = "http://hots/T.php";
private String urls = "http://host/S.php";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.abmeldung);

textViewSpiel = (TextView) findViewById(R.id.textViewSpiel);
switchSpiel = (Switch) findViewById(R.id.switchSpiel);
textViewTraining = (TextView) findViewById(R.id.textViewTraining);
switchTraining = (Switch) findViewById(R.id.switchTraining);

SharedPreferences sharedPrefs1 = getSharedPreferences("SwitchSpiel", MODE_PRIVATE);
switchSpiel.setChecked(sharedPrefs1.getBoolean("ValueSwitchSpiel", true));

SharedPreferences sharedPrefs2 = getSharedPreferences("SwitchTraining", MODE_PRIVATE);
switchTraining.setChecked(sharedPrefs2.getBoolean("ValueSwitchTraining", true));

zurueck = (Button) findViewById(R.id.zurueck);
zurueck.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Abmeldung.this, Main.class));
}
});/**
* Import Varbiable firstN aus SQlite für MySQl update
**/
DatabaseHandler db = new DatabaseHandler(getApplicationContext());

/**
* Hashmap to load data from the Sqlite database
**/
HashMap<String, String> user = new HashMap<String, String>();
user = db.getUserDetails();

final String firstN = user.get("fname");// SPIEL
//set the Switch on
//switchSpiel.setChecked(true);
//attach a listener to check for changes in state
switchSpiel.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked)
{
if (isChecked) {
SharedPreferences.Editor editor = getSharedPreferences("SwitchSpiel", MODE_PRIVATE).edit();
editor.putBoolean("ValueSwitchSpiel", true);
editor.commit();
textViewSpiel.setText("dabei!");
spiel_anmel1 = "Ja";

} else
{
SharedPreferences.Editor editor = getSharedPreferences("SwitchSpiel", MODE_PRIVATE).edit();
editor.putBoolean("ValueSwitchSpiel", false);
editor.commit();
textViewSpiel.setText("nicht dabei :-(.");
spiel_anmel1 = "Nein";

}
}
});
//check the current state before we display screen
if (switchSpiel.isChecked()) {
textViewSpiel.setText("dabei!");
} else {
textViewSpiel.setText("nicht dabei :-(.");
}

switchSpiel.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
firstname=firstN.toString();
spiel_anmel = spiel_anmel1.toString();

switchSpiel();
}
});
// Training
//set the Switch on
//switchTraining.setChecked(true);
//attach a listener to check for changes in state
switchTraining.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {

if (isChecked) {
SharedPreferences.Editor editor = getSharedPreferences("SwitchTraining", MODE_PRIVATE).edit();
editor.putBoolean("ValueSwitchTraining", true);
editor.commit();
textViewTraining.setText("am Start!!!");
} else {
SharedPreferences.Editor editor = getSharedPreferences("SwitchTraining", MODE_PRIVATE).edit();
editor.putBoolean("ValueSwitchTraining", false);
editor.commit();
textViewTraining.setText("eine faule Sau!");
}
}
});

//check the current state before we display screen
if (switchTraining.isChecked()) {
textViewTraining.setText("am Start!!!");
} else {
textViewTraining.setText("eine faule Sau!");
}
}//Update MYSQL SPIEL (switchSpiel())

public void switchSpiel() {
new DownloadWebpageTask().execute(urls, firstname, spiel_anmel);
}

private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
//params comes from execute call: params[o] is the url
try
// Initializing parameters
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("firstname", urls[1]));
nameValuePairs.add(new BasicNameValuePair("spiel_anmel", urls[2]));

//Make HTTP Request
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urls[0]);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();

// Read the response

BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();

// Return the response
return result;
} catch (IOException e) {
return "Unable to retrieve web page. Url may be invalid.";
}
}

} }

мой S.php

$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");

$name=$_REQUEST['firstname'];
$training=$_REQUEST['spiel_anmel'];

$flag['code']=0;

if($r = mysql_query("UPDATE users SET spiel_anmel = '$training' WHERE firstname ='$name'", $con)) {
$flag['code']=1;
}

print(json_encode($flag));
mysql_close($con);

Я обновляю код Java, потому что реализовал две кнопки для отправки положения переключателя. Теперь я получаю org.json.JSONException: конец ввода в символе 0 из.

public class Abmeldung extends Activity {
Button zurueck;
private TextView textViewSpiel;
private TextView textViewTraining;
private Switch switchSpiel;
private Switch switchTraining;
//String firstname;
String spiel_anmel;
InputStream is = null;
String result = null;
String line = null;
String username;
String sa;
int code;
private String urlt = "http://.../insertA.php";
private String urls = "http://.../insertB.php";@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.abmeldung);

textViewSpiel = (TextView) findViewById(R.id.textViewSpiel);
switchSpiel = (Switch) findViewById(R.id.switchSpiel);
textViewTraining = (TextView) findViewById(R.id.textViewTraining);
switchTraining = (Switch) findViewById(R.id.switchTraining);

SharedPreferences sharedPrefs1 = getSharedPreferences("SwitchSpiel", MODE_PRIVATE);
switchSpiel.setChecked(sharedPrefs1.getBoolean("ValueSwitchSpiel", true));

SharedPreferences sharedPrefs2 = getSharedPreferences("SwitchTraining", MODE_PRIVATE);
switchTraining.setChecked(sharedPrefs2.getBoolean("ValueSwitchTraining", true));

zurueck = (Button) findViewById(R.id.zurueck);
zurueck.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Abmeldung.this, Main.class));
}
});/**
* Import Varbiable userid aus SQlite für MySQl update
**/
DatabaseHandler db = new DatabaseHandler(getApplicationContext());

/**
* Hashmap to load data from the Sqlite database
**/
HashMap<String, String> user = new HashMap<String, String>();
user = db.getUserDetails();

final String uname = user.get("uname");

// SPIEL
//set the Switch on
//switchSpiel.setChecked(true);
//attach a listener to check for changes in state
switchSpiel.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
SharedPreferences.Editor editor = getSharedPreferences("SwitchSpiel", MODE_PRIVATE).edit();
editor.putBoolean("ValueSwitchSpiel", true);
editor.commit();
textViewSpiel.setText("dabei!");
spiel_anmel = "Ja";

} else {
SharedPreferences.Editor editor = getSharedPreferences("SwitchSpiel", MODE_PRIVATE).edit();
editor.putBoolean("ValueSwitchSpiel", false);
editor.commit();
textViewSpiel.setText("nicht dabei :-(.");
spiel_anmel = "Nein";

}

}

});
//check the current state before we display screen
if (switchSpiel.isChecked()) {
textViewSpiel.setText("dabei!");
} else {
textViewSpiel.setText("nicht dabei :-(.");
}// Training
//set the Switch on
//switchTraining.setChecked(true);
//attach a listener to check for changes in state
switchTraining.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {

if (isChecked) {
SharedPreferences.Editor editor = getSharedPreferences("SwitchTraining", MODE_PRIVATE).edit();
editor.putBoolean("ValueSwitchTraining", true);
editor.commit();
textViewTraining.setText("am Start!!!");
} else {
SharedPreferences.Editor editor = getSharedPreferences("SwitchTraining", MODE_PRIVATE).edit();
editor.putBoolean("ValueSwitchTraining", false);
editor.commit();
textViewTraining.setText("eine faule Sau!");
}
}
});

//check the current state before we display screen
if (switchTraining.isChecked()) {
textViewTraining.setText("am Start!!!");
} else {
textViewTraining.setText("eine faule Sau!");
}

//final String spielan = spiel_anmel;
Button updates = (Button) findViewById(R.id.updates);

updates.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sa = spiel_anmel.toString();
username = uname.toString();
updates();
}
});
}//UPdate MYSQL SPIEL (switchSpiel())

public void updates() {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

nameValuePairs.add(new BasicNameValuePair("uname", username));
nameValuePairs.add(new BasicNameValuePair("spiel_anmel", sa));

try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urls);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Adress",
Toast.LENGTH_LONG).show();
}

try {
BufferedReader readers = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sbs = new StringBuilder();
while ((line = readers.readLine()) != null) {
sbs.append(line + "\n");
}
is.close();
result = sbs.toString();
Log.e("pass 2", "connection success");
} catch (Exception e) {
Log.e("Fail 2", "Error converting result "+ e.toString());
}

try {
JSONObject json_datas = new JSONObject(result);
code = (json_datas.getInt("code"));

if (code == 1) {
Toast.makeText(getBaseContext(), "Update Successfully",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Sorry, Try Again",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
}
}

Соответствующий php:

$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");

$uname=$_REQUEST['uname'];
$spiel=$_REQUEST['spiel_anmel'];

$flag['code']=0;

if($r=mysql_query("UPDATE users SET spiel_anmel = 'spiel' WHERE uname LIKE 'uname'",$con))
{
$flag['code']=1;
}

print(json_encode($flag));
mysql_close($con);

Есть идеи?

0

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …