Android : How to add radio button result in MySql database using php in android.

on Tuesday, September 16, 2014


I am making a quiz app in android. In my app, i have two activities. On first activity I am displaying questions and their corresponding options from mysql database and displaying as a list view. I have done this thing successfully. Now, I want to store my answers of questions in a different table i n the database.


Here is my QuizActivity



package com.aquib.quiz;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
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.ListAdapter;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class QuizActivity extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> productsList;

// url to get all products list
private static String url_all_products = "http://labs.kamkazi.com/aquib/quiz/quiz.php";
private static String url_write_answer = "http://labs.kamkazi.com/aquib/quiz/write_answer.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_WRITE = "success1";
private static final String TAG_PRODUCTS = "quiz";
private static final String TAG_QUESTIONID = "question_id";
private static final String TAG_QUESTIONTITLE = "question_title";
private static final String TAG_OPTION1 = "option1";
private static final String TAG_OPTION2 = "option2";
private static final String TAG_OPTION3 = "option3";
private static final String TAG_OPTION4 = "option4";

// products JSONArray
JSONArray products = null;

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

// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();

// Loading products in Background Thread
new LoadAllProducts().execute();

}

public void addRowBtn(View button) {

new InsertAnswer().execute();
}

class InsertAnswer extends AsyncTask<String, String, String> {

@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String answer = null;

RadioButton rBtn1 = (RadioButton) findViewById(R.id.rdButton1);
RadioButton rBtn2 = (RadioButton) findViewById(R.id.rdButton2);
RadioButton rBtn3 = (RadioButton) findViewById(R.id.rdButton3);
RadioButton rBtn4 = (RadioButton) findViewById(R.id.rdButton4);

if (rBtn1.isSelected()) {
answer = rBtn1.getText().toString();
}
if (rBtn2.isSelected()) {
answer = rBtn1.getText().toString();
}
if (rBtn3.isSelected()) {
answer = rBtn3.getText().toString();
}
if (rBtn4.isSelected()) {
answer = rBtn4.getText().toString();
}

// Building Parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("answer", answer));

// getting JSON Object
// Note that write answer url accepts POST method
JSONObject json = jParser.makeHttpRequest(url_write_answer, "POST",
params1);

// Check Log cat for response
Log.d("Create Response", json.toString());

// Check for success tag
try {
int success1 = json.getInt(TAG_WRITE);

if (success1 == 1) {
// successfully create answer
Intent intent = new Intent(getApplicationContext(),
ResultActivity.class);
startActivity(intent);

// closing this screen
finish();
} else {
// failed to create product
Log.i("Failed Message", "Failed to insert");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

}

/**
* 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(QuizActivity.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 reponse
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_PRODUCTS);

// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);

// Storing each json item in variable
String questionTitle = c.getString(TAG_QUESTIONTITLE);
String option1 = c.optString(TAG_OPTION1);
String option2 = c.optString(TAG_OPTION2);
String option3 = c.optString(TAG_OPTION3);
String option4 = c.optString(TAG_OPTION4);
String questionid = c.optString(TAG_QUESTIONID);

// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();

// adding each child node to HashMap key => value

map.put(TAG_QUESTIONID, questionid);
map.put(TAG_QUESTIONTITLE, questionTitle);
map.put(TAG_OPTION1, option1);
map.put(TAG_OPTION2, option2);
map.put(TAG_OPTION3, option3);
map.put(TAG_OPTION4, option4);

// adding HashList to ArrayList
productsList.add(map);

}
} else {
Toast myToast = Toast.makeText(getApplicationContext(),
"No quiz found", Toast.LENGTH_SHORT);
myToast.show();
}
} 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();

ListAdapter adapter = new SimpleAdapter(QuizActivity.this,
productsList, R.layout.list_item, new String[] {
TAG_QUESTIONID, TAG_QUESTIONTITLE, TAG_OPTION1,
TAG_OPTION2, TAG_OPTION3, TAG_OPTION4 }, new int[] {
R.id.questionId, R.id.questionName, R.id.rdButton1,
R.id.rdButton2, R.id.rdButton3, R.id.rdButton4 });

// updating listview
setListAdapter(adapter);

}

}
}


This is my php file



<?php


$con = mysql_connect("localhost", "kamka6ac_quiz", "mayajaal");
if (!$con) {
die('Could not connect: ' . mysql_error());
}

mysql_select_db("kamka6ac_quiz", $con);

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['answer']) ) {

$answer = $_POST['answer'];

// mysql inserting an answer
$result = mysql_query("INSERT INTO answers(answer_id,answer) VALUES(' ', '$answer')");

// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success1"] = 1;
$response["message"] = "Answer successfully inserted.";

// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success1"] = 0;
$response["message"] = "Oops! An error occurred.";

// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success1"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}
?>


In my database I have a table name answers which have two columns named answer_id and answer. When I click submit button, in my table only answer_id column value is inserted. But only single value is inserted and in actual i have many questions on my list activity.


Please don't warn me for sqli or pdo for sql injection as this app is only for practice.


0 comments:

Post a Comment