我想使用从服务器获取值来创建侧边栏。 但是我试图从保存返回值的方法获取的值导致错误。我无法称之为这种方法。
以下是代码:
public class MainActivity extends AppCompatActivity {
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
public String returnnumfromAsyncTask;
private TextView setTextValue;
private TextView textViewid;
private Button buttonHit;
private String var;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
/*textViewid = (TextView)findViewById(R.id.textViewid);
buttonHit = (Button)findViewById(R.id.buttonHit);
buttonHit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new JSONTask().execute("http://xyz.co/tests/ems/query.php");
}
});*/
}
private void addDrawerItems() {
new JSONTask().execute("http://xyz.co/tests/ems/query.php");
JSONTask json = new JSONTask();
String myArray = json.myMethod();
String[] osArray = { "Android", "iOS", "Windows", "OS X", "Linux" };
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Time for an upgrade!", Toast.LENGTH_SHORT).show();
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Navigation!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class JSONTask extends AsyncTask<String,String,String> {
@Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection)url.openConnection();
connection.connect();
// connecting to the url
//Reading the data in bytes stream
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
//Reading the data by creating a buffer
StringBuffer buffer = new StringBuffer();
String line="";
while((line = reader.readLine())!= null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
List<String> list = new ArrayList<String>();
JSONArray array = parentObject.getJSONArray("kitten");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("if")+"\n");
}
/*String finalObject = parentObject.getString("name");
JSONArray parentArray = parentObject.getJSONArray("kitten");
StringBuffer finalBufferedData = new StringBuffer();
for(int i=0;i<parentArray.length();i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
int curr = finalObject.getInt("name");
//int bus = finalObject.getInt("bus");
finalBufferedData.append(curr + "\n" );
}*/
//return finalBufferedData.toString();
return list.toString();
// setting text view from the url
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally{
if(connection !=null) {
connection.disconnect();
}
try {
if (reader != null)
{
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//textViewid.setText(result);
myMethod(result);
}
public String myMethod(String result){
return result;
}
}
}
注意这一行:
String myArray = json.myMethod();
它试图调用一个函数myMethod(),它返回一个字符串值,或者更确切地说是一个通过执行asynctask得到的数组。
但不知怎的,我无法从JSON asynctask函数调用myMethod。 所以我的主要问题是如何调用一个返回值的方法,从而在我的代码中使用它?
提前致谢
答案 0 :(得分:1)
因为doInBackground
类的JSONTask
方法在后台线程中执行,所以:
JSONTask json = new JSONTask();
String myArray = json.myMethod();
这些行在调用execute
方法之后正在执行。
EITHER
使用AsyncTask.get()
方法冻结UI线程,直到doInBackground
方法执行未完成。
OR
最好的方法是使用onPostExecute
为ListView设置适配器。
编辑:
评论中的问题:
如何使用onPostExecute为ListView设置适配器?
如果JSONTask
类是MainActivity
类的内部类,则可以直接访问MainActivity
中JSONTask
类的所有变量。只需在{{1}中移动相关代码方法。
如果onPostExecute
类是单独的类,则将Activity Context传递给JSONTask
,以便从普通java类访问UI元素:
1。将构造函数添加到JSONTask
类以获取活动上下文:
JSONTask
2。在创建private Context mContext;
private ListView mDrawerList;
JSONTask(Context mContext, ListView mDrawerList){
this.mContext=mContext;
this.mDrawerList=mDrawerList;
}
类对象时,将MainActivity.this
作为参数传递:
JSONTask
3。现在使用 JSONTask objJSONTask=new JSONTask(MainActivity.this);
objJSONTask.execute("http://xyz.co/tests/ems/query.php");
和mDrawerList在mContext
答案 1 :(得分:1)
AsyncTask.doInBackground()
以异步方式运行。
您应该像这样运行JSONTask
:
private void addDrawerItems() {
new JSONTask().execute("http://xyz.co/tests/ems/query.php");
}
将使用此任务结果的代码移至JSONTask.onPostExecute()
:
public class JSONTask extends AsyncTask<String,String,String[]> {
@Override
protected String[] doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection)url.openConnection();
connection.connect();
//connecting to the url
//Reading the data in bytes stream
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
// Reading the data by creating a buffer
StringBuffer buffer = new StringBuffer();
String line="";
while((line = reader.readLine())!= null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
List<String> list = new ArrayList<String>();
JSONArray array = parentObject.getJSONArray("kitten");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("if")+"\n");
}
return list.toArray(new String[list.size()]);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally{
if(connection !=null) {
connection.disconnect();
}
try {
if (reader != null)
{
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String[] result) {
mAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, result);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Time for an upgrade!", Toast.LENGTH_SHORT).show();
}
});
}
}