2
我目前正在開發一個android項目,我希望能夠按下一個按鈕,並且它會將用戶數據顯示到另一個活動的列表視圖中。我目前在某種意義上工作,但它需要我按兩個按鈕。一個從mysql數據庫獲取json數據,然後另一個將數據發送到下一個允許我顯示它的活動。Android:獲取並解析json數據到列表視圖
我希望能有一種方法,這些方法都可以通過單擊一次按鈕來運行,或者在一個方法中都有。因爲onPostExecute
大幹快上UI
線程執行
public class MyMainActivity extends AppCompatActivity {
String url = "http://192.168.20.120";
String json_string;
View v;
//Button to get the data
ImageButton getUserDetailsBtn;
//Button to parse the data
ImageButton parseUserDetailsBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_main);
getUserDetailsBtn= (ImageButton)findViewById(R.id.getUserDetailsButton);
parseUserDetailsBtn = (ImageButton)findViewById(R.id.parseUserDetailsButton);
getUserDetailsBtn.setVisibility(View.GONE);
}
//
//get user details in app
//
public void getDetails(View view) {
new LoadUserDetails().execute();
parseUserDetailsBtn .setVisibility(View.GONE);
getUserDetailsBtn= .setVisibility(View.VISIBLE);
}
//Load the user details
class LoadUserDetails extends AsyncTask<Void,Void,String>
{
String json_url;
String JSON_STRING;
@Override
protected void onPreExecute() {
json_url = url+"/getUserDetails.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 (MalformedJsonException 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) {
TextView textview = (TextView) findViewById(R.id.textview);
textview.setText("");
json_string = result;
}
}
//
//parse the data
//
public void parseJSON(View view)
{
if(json_string==null){
Toast.makeText(getApplicationContext(), "First get JSON Data", Toast.LENGTH_LONG).show();
}
else{
Intent intent = new Intent(this, ShowUserActivity.class);
intent.putExtra("json_data", json_string);
startActivity(intent);
}
}
這就是我想會的工作,但是當我把它放在onPostExecute()像你這樣我得到一個錯誤意圖說「無法解析構造函數意圖」。有任何想法嗎? – Dsk
使用'MyMainActivity.this'代替'this' –
謝謝我的朋友! – Dsk