这实际上是一个用于参加测验的Android应用程序。问题及其选项分别显示在文本视图和单选按钮中。此外,JSON中还有正确的答案,可以检查以计算得分。我需要帮助将JSON访问权限从Assets目录更改为URL。
public class Test extends Activity implements View.OnClickListener{
TextView txt_question,txt_timer,txt_score;
RadioButton rb1,rb2,rb3,rb4,rb5;
RadioGroup rg;
Button btn_skip, btn_next;
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
public int flag = 0;
public int score;
private JSONArray jsonArray;
private String rightAnswer;
CountDownTimer cT;
int time;
Dialog restartdialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
// Creating new JSON Parser
initializeScreen();
sb = readJsonFromAssets();
String myjsonstring = sb.toString();
txt_timer=(TextView) findViewById(R.id.timer);
time=(int)getIntent().getExtras().getInt("timer");
score=0;
btn_next=(Button) findViewById(R.id.next);
rg=(RadioGroup) findViewById(R.id.radioGroup);
restartdialog= new Dialog(Test.this);
restartdialog.setContentView(R.layout.restart);
restartdialog.setTitle("Want to try again?");
Button btnyes=(Button)restartdialog.findViewById(R.id.yes);
btnyes.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
flag = 0;
reInflateView(jsonArray.getJSONObject(flag));
txt_score.setText("" + score);
score = 0;
restartdialog.dismiss();
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
time = (int) getIntent().getExtras().getInt("timer");
Button btnno=(Button)restartdialog.findViewById(R.id.no);
btnno.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
btn_next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String selectedAns = "";
try {
if (flag < jsonArray.length()) {
switch (rg.getCheckedRadioButtonId()) {
case R.id.option1:
selectedAns = "Option1";
flag++;
cT.start();
break;
case R.id.option2:
selectedAns = "Option2";
flag++;
cT.start();
break;
case R.id.option3:
selectedAns = "Option3";
flag++;
cT.start();
break;
case R.id.option4:
selectedAns = "Option4"; // These are the options that are to be selected.
flag++;
cT.start();
break;
case R.id.option5:
selectedAns = "Option5";
flag++;
cT.start();
break;
default:
Toast.makeText(Test.this,"Please Select one option or skip to next question",Toast.LENGTH_SHORT).show();
break;
}
if (rightAnswer.equalsIgnoreCase(selectedAns)) {
++score;
txt_score.setText("" + score);
}
if (flag == jsonArray.length()) {
restartdialog.setTitle("You Scored "+score+" out of "+flag+", Want to try again?");
restartdialog.setCancelable(false);
restartdialog.show();
score = 0;
} else {
reInflateView(jsonArray.getJSONObject(flag));
}
}
} catch (Exception e) {
e.printStackTrace();
}
rg.clearCheck();
}
});
btn_skip=(Button) findViewById(R.id.skip);
btn_skip.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
time=(int)getIntent().getExtras().getInt("timer");
if(flag == jsonArray.length()-1){
restartdialog.setTitle("You Scored "+score+" out of "+flag+", Want to try again?");
restartdialog.setCancelable(false);
restartdialog.show();
flag=0;
score = 0;
} else {
flag++;
reInflateView(jsonArray.getJSONObject(flag));
}
cT.start();
}catch (Exception e){
e.printStackTrace();
}
rb1.setEnabled(true);
rb2.setEnabled(true);
rb3.setEnabled(true);
rb4.setEnabled(true);
rb5.setEnabled(true);
btn_next.setEnabled(true);
rg.clearCheck();
}
});
cT = new CountDownTimer(time*1000, 1000) {
public void onTick(long millisUntilFinished) {
txt_timer.setTextColor(Color.BLACK);
txt_timer.setText("" + millisUntilFinished / 1000);
}
public void onFinish() {
txt_timer.setText("Time over for this question");
txt_timer.setTextColor(Color.RED);
rb1.setEnabled(false);
rb2.setEnabled(false);
rb3.setEnabled(false);
rb4.setEnabled(false);
rb5.setEnabled(false);
btn_next.setEnabled(false);
}
};
cT.start();
try {
JSONObject jsonObjMain = new JSONObject(myjsonstring);
jsonArray = jsonObjMain.getJSONArray("questions");
reInflateView(jsonArray.getJSONObject(flag));
} catch (JSONException e) {
e.printStackTrace();
}
txt_score.setText(""+score);
}
private StringBuffer readJsonFromAssets() {
int type=(int)getIntent().getExtras().getInt("timer");
StringBuffer sb = new StringBuffer();
try {
if(type==40) {
br = new BufferedReader(new InputStreamReader(getAssets().open("queshard.json")));
}
else if(type==30)
{
br = new BufferedReader(new InputStreamReader(getAssets().open("quesmedium.json")));
}
else
{
br = new BufferedReader(new InputStreamReader(getAssets().open("queseasy.json")));
}
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb;
}
private void initializeScreen() {
txt_question = (TextView) findViewById(R.id.ques);
rb1 = (RadioButton) findViewById(R.id.option1);
rb2 = (RadioButton) findViewById(R.id.option2);
rb3 = (RadioButton) findViewById(R.id.option3);
rb4 = (RadioButton) findViewById(R.id.option4);
rb5 = (RadioButton) findViewById(R.id.option5);
txt_score=(TextView) findViewById(R.id.score);
}
private void reInflateView(JSONObject jsonObj) {
try {
String question = jsonObj.getString("ques");
String optionA = jsonObj.getString("Option1");
String optionB = jsonObj.getString("Option2");
String optionC = jsonObj.getString("Option3");
String optionD = jsonObj.getString("Option4");
String optionE = jsonObj.getString("Option5");
rightAnswer = jsonObj.getString("correct_answer_index");
txt_question.setText(""+(flag+1)+") "+question);
rb1.setOnClickListener(null);
rb2.setOnClickListener(null);
rb3.setOnClickListener(null);
rb4.setOnClickListener(null);
rb5.setOnClickListener(null);
rb1.setText(optionA);
rb2.setText(optionB);
rb3.setText(optionC);
rb4.setText(optionD);
rb5.setText(optionE);
rb1.setChecked(false);
rb1.setOnClickListener(this);
rb2.setChecked(false);
rb2.setOnClickListener(this);
rb3.setChecked(false);
rb3.setOnClickListener(this);
rb4.setChecked(false);
rb4.setOnClickListener(this);
rb5.setChecked(false);
rb5.setOnClickListener(this);
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void onBackPressed() {
final Dialog dialog = new Dialog(Test.this);
dialog.setContentView(R.layout.back);
dialog.setTitle("Are You Sure?");
dialog.setCancelable(false);
Button btnok=(Button)dialog.findViewById(R.id.ok);
btnok.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
Button btncancel=(Button)dialog.findViewById(R.id.cancel);
btncancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
@Override
public void onClick(View v) {
}
}
以下是ABC_URL上的JSON文件,该文件将从URL而不是资源文件中提取:
{
"questions": [
{
"ques": "Super class of every class?",
"Option1": "class",
"Option2": "Class",
"Option3": "Object",
"Option4": "Java",
"Option5": "None of the above",
"correct_answer_index": "Option3"
},
{
"ques": "Which class cannot be a subclass in java?",
"Option1": "Abstract class",
"Option2": "Parent class",
"Option3": "Final class",
"Option4": "All of the above",
"Option5": "None of the above",
"correct_answer_index": "Option3"
},
{
"ques": " Suspend thread can be revived by using",
"Option1": "Start() method",
"Option2": "Suspend() method",
"Option3": "resume() method",
"Option4": "yield() method",
"Option5": "None of the above",
"correct_answer_index": "Option3"
},
{
"ques": "Runnable is : ",
"Option1": "Class",
"Option2": "Method",
"Option3": "Variable",
"Option4": "Interface",
"Option5": "None of the above",
"correct_answer_index": "Option4"
},
{
"ques": "Which collection class associates values witch keys, and orders the keys according to their natural order ?",
"Option1": "java.util.HashSet",
"Option2": "java.util.LinkedList",
"Option3": "java.util.TreeMap",
"Option4": "java.util.SortedSet",
"Option5": "None of the above",
"correct_answer_index": "Option3"
},
{
"ques": "Which method is used to perform DML statements in JDBC?",
"Option1": "execute()",
"Option2": "executeUpdate()",
"Option3": "executeQuery()",
"Option4": "executeNonQuery()",
"Option5": "None of the above",
"correct_answer_index": "Option2"
},
{
"ques": "Which of the following below are valid isolation levels in J2EE?",
"Option1": "TRANSACTION_READ_UNCOMMITTED",
"Option2": "TRANSACTION_SERIALIZABLE",
"Option3": "Only A",
"Option4": "Only B",
"Option5": "Both A and B",
"correct_answer_index": "Option5"
},
{
"ques": "Which methods are utilized to control the access to an object in multi threaded programming?",
"Option1": "Asynchronized methods",
"Option2": "Synchronized methods",
"Option3": "Serialized methods",
"Option4": "All of the above",
"Option5": "None of the above",
"correct_answer_index": "Option2"
},
{
"ques": "Program which executes applet is known as :",
"Option1": "Applet engine",
"Option2": "Virtual machine",
"Option3": "JVM",
"Option4": "JRE",
"Option5": "None of the above",
"correct_answer_index": "Option1"
},
{
"ques": "Which statement is static and synchronized in JDBC API?",
"Option1": "executeQuery()",
"Option2": "executeUpdate()",
"Option3": "getConnection()",
"Option4": "prepareCall()",
"Option5": "None of the above",
"correct_answer_index": "Option3"
},
{
"ques": "The JDBC-ODBC bridge is",
"Option1": "Multithreaded",
"Option2": "Singlethreaded",
"Option3": "Asyncthread",
"Option4": "All of the above",
"Option5": "None of the above",
"correct_answer_index": "Option1"
},
{
"ques": "All raw data types should be read and uploaded to the database as an array of :",
"Option1": "Int",
"Option2": "Char",
"Option3": "Boolean",
"Option4": "Double",
"Option5": "Byte",
"correct_answer_index": "Option5"
}
]
}
答案 0 :(得分:0)
您可以使用以下方法通过在方法中传递url来解析Json:
public String executeRequest(String url, Activity context) {
long startTime = System.currentTimeMillis();
TAG = NetworkRequest.class.getSimpleName();
Log.i(TAG, "WEBSERVICE URL--------------- " + url);
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
Constants.CONNECTION_TIME_OUT);
HttpConnectionParams.setSoTimeout(httpParams,
Constants.SOCKET_TIME_OUT);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Content-Type", "text/xml; charset=utf-8");
httpGet.addHeader("Cache-Control", "No-Cache");
String serverResponse = null;
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
ResponseHandler<String> responseHandler = new
BasicResponseHandler();
serverResponse = responseHandler.handleResponse(httpResponse);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
Log.i(TAG, " Successfull, STATUS CODE: " + statusCode);
return serverResponse;
} else {
Log.i(TAG, "Failure, STATUS CODE: " + statusCode);
return null;
}
} catch (MalformedChallengeException e) {
e.printStackTrace();
return null;
} catch (AuthenticationException e) {
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (IllegalArgumentException exception) {
exception.printStackTrace();
return null;
} finally {
httpClient.getConnectionManager().shutdown();
}
return serverResponse;
}