以下代码中的所有内容均有效,除非用户单击其中一个按钮以快速进行连接而没有时间连接数据库并获取json值。
我试图包围try catch块,并尝试检查是否创建了一个if语句来检查第一个字符=='{',因为这始终是给定json字符串中的第一个字符。
这是课程
package com.example.allrateform;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import static com.example.allrateform.MainActivity.UsernameText;
public class Categories extends AppCompatActivity {
public static String Category;
public static char[] TextList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categories);
//CREATING ALL INSTANCES
final Button ComputersButton=(Button)findViewById(R.id.ComputersButton);
final Button HobbiesButton=(Button)findViewById(R.id.HobbiesButton);
final Button BooksButton=(Button)findViewById(R.id.BooksButton);
final Button TourismButton=(Button)findViewById(R.id.TourismButton);
final Button GamesButton=(Button)findViewById(R.id.GamesButton);
final Button FantasyButton=(Button)findViewById(R.id.FantasyButton);
final Button SportsButton=(Button)findViewById(R.id.SportsButton);
final TextView TextViewUsername=(TextView)findViewById(R.id.TextViewUsername);
TextViewUsername.setText(UsernameText);
getJSON();
ComputersButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Category="Computers";
openQuestion();
}
});
HobbiesButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Category="Hobbies";
openQuestion();
}
});
BooksButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Category="Books";
openQuestion();
}
});
TourismButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Category="Tourism";
openQuestion();
}
});
GamesButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Category="Games";
openQuestion();
}
});
FantasyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Category="Fantasy";
openQuestion();
}
});
SportsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Category="Sports";
openQuestion();
}
});
}
public void openQuestion(){
try {
Intent intent = new Intent(this, Question.class);
startActivity(intent);
}catch(Exception ex) {
AlertDialog.Builder builder = new AlertDialog.Builder(Categories.this);
builder.setMessage("Try again later")
.setNegativeButton("Ok", null)
.create()
.show();
}
}
public void getJSON() {
new Categories.BackgroundTask().execute();
}
class BackgroundTask extends AsyncTask<Void, Void, String> {
String json_url;
String JSON_STRING;
@Override
protected void onPreExecute() {
json_url = "https://allratejohnnycode.000webhostapp.com/List.php";
}
@Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()) != null) {
stringBuilder.append(JSON_STRING + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
TextList=result.toCharArray();
}
}
}
答案 0 :(得分:0)
我想提供两种不同的方法。
第一个是您要的,尽管我建议第二个一个:
您可以维护一个boolean
来表示是否加载了JSON
,
因此,当用户单击按钮时,首先要检查布尔状态。如果已加载-继续进行意图创建。否则-提供循环进度加载程序,该加载程序将等待JSON加载。 (如果需要帮助,请评论我,我会为您提供代码示例。)
这是一个更“繁重的”解决方案,但是研究Android Architecture Components后,您将认识到这是在后台加载数据的最干净,最有效的方法,同时总体上保持了数据和UI之间的分隔。非常有用的知识。
第1步:添加进度条,开头为visibility="gone"
。随心所欲设计。
第2步:尝试使用此代码。它有效(经过测试)。
public class Categories extends AppCompatActivity {
public static String Category;
public static char[] TextList;
//4 new variables
private static volatile boolean isJsonLoaded, isButtonClicked;
private ProgressBar progressBar;
private final Object locker = 0; //for concurrent modification & synchronization
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categories);
TextView TextViewUsername = findViewById(R.id.TextViewUsername);
TextViewUsername.setText(UsernameText);
this.progressBar = findViewById(R.id.progressBar);
isJsonLoaded = false;
isButtonClicked = false;
initButtons();
getJSON();
}
//Slightly beautified your code
private void initButtons() {
//Temp array of buttons
ArrayList<Button> buttons = new ArrayList<>(Arrays.asList(
(Button) findViewById(R.id.ComputersButton),
(Button) findViewById(R.id.HobbiesButton),
(Button) findViewById(R.id.BooksButton),
(Button) findViewById(R.id.TourismButton),
(Button) findViewById(R.id.GamesButton),
(Button) findViewById(R.id.FantasyButton),
(Button) findViewById(R.id.SportsButton)
));
//Mutual 'onClick' listener for all of them
View.OnClickListener buttonClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
//Get the button's name
String buttonName = getResources().getResourceEntryName(v.getId());
//Eliminate the "...Button" part
Category = buttonName.substring(0, buttonName.indexOf("Button"));
handleButtonClick();
}
};
for (Button button : buttons)
button.setOnClickListener(buttonClick);
}
public void handleButtonClick() {
synchronized (locker) {
if (isJsonLoaded) openQuestion();
else {
isButtonClicked = true;
//Show the progress bar
progressBar.setVisibility(View.VISIBLE);
}
}
}
void openQuestion() {
Intent intent = new Intent(this, Question.class);
startActivity(intent);
}
public void getJSON() {
new Categories.BackgroundTask().execute();
}
class BackgroundTask extends AsyncTask<Void, Void, String> {
String json_url;
String JSON_STRING;
@Override
protected void onPreExecute() {
json_url = "https://allratejohnnycode.000webhostapp.com/List.php";
}
@Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()) != null) {
stringBuilder.append(JSON_STRING + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
TextList = result.toCharArray();
isJsonLoaded = true;
synchronized (locker) {
if (isButtonClicked)
openQuestion();
}
//Hide the progress bar
progressBar.setVisibility(View.GONE);
}
}
}