Android - 在通过AsyncTask提取JSON数据后,无法将数据发送到下一个活动(扩展ListActivity)

时间:2014-11-04 08:32:42

标签: android android-asynctask

首先,我是一名机器人新手 我正在创建一个简单的应用程序,它通过PHP脚本从服务器中提取一些数据,并在下一个Activity中的ListView中显示它们。但是,我发现如果脚本没有返回任何内容,则应用程序崩溃。所以我保持检查,只有当脚本返回一些数据时,应用程序才会切换到下一个活动。
这是我的代码。

public class HomeScreen extends ActionBarActivity {

String message3;
String message_short;
String[] items;
String[] short_items;
int check = 0;

private ProgressDialog dialog;

public String readJSONFeed(String URL)
{
    StringBuilder sb = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet hg = new HttpGet(URL);
    try
    {
        HttpResponse response = client.execute(hg);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if(statusCode == 200)
        {
            HttpEntity en = response.getEntity();
            InputStream content = en.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while((line = reader.readLine()) != null)
            {
                sb.append(line);
            }
        }
        else
        {
            Log.e("JSON", "Failed to download File");
        }
    }
    catch(ClientProtocolException e)
    {
        e.printStackTrace();
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    return sb.toString();
}

private class ReadJSONFeedTask extends AsyncTask<String, Void, String>
{
    protected void onPreExecute()
    {
        super.onPreExecute();
        dialog = new ProgressDialog(HomeScreen.this);
        dialog.setMessage("Downloading Notifications. Please wait . . .");
        dialog.setIndeterminate(false);
        dialog.setCancelable(false);
        dialog.show();
    }
    protected String doInBackground(String...urls)
    {
        return readJSONFeed(urls[0]);
    }
    protected void onPostExecute(String result)
    {
        dialog.dismiss();
        try
        {
            JSONArray jsonArray = new JSONArray(result);
            items = new String[jsonArray.length()];
            short_items = new String[jsonArray.length()];
            for(int i = 0; i < jsonArray.length(); i++)
            {
                JSONObject jobj = jsonArray.getJSONObject(i);
                message3 = "SUBJECT : " + jobj.getString("subject") + "\n\n" + 
                        "DATE : " + jobj.getString("date") + "\n" + jobj.getString("time") + "\n\n"
                         + "NOTICE : " + jobj.getString("notice");
                message_short = "SUBJECT : " + jobj.getString("subject") + "\n" 
                        + "NOTICE : " + jobj.getString("notice").substring(0, 20) + "..."
                        + "\n" + jobj.getString("time");
                items[i] = message3;
                short_items[i] = message_short;

                check += 1;
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_screen);
}

public void notificationPane(View view)
{

    String localhost = "http://10.0.2.2/example/json/notification.php";
    new ReadJSONFeedTask().execute(localhost);

    if(check != 0)
    {
        Intent i = new Intent(HomeScreen.this, NotificationPanel.class);
        i.putExtra("items", items);
        i.putExtra("short_items", short_items);
        startActivity(i);
    }
    else
    {
        Toast.makeText(getBaseContext(), "Either there is no notification to display or there might be a problem with your internet connection.", Toast.LENGTH_SHORT).show();
    }
}

public void recentNotice(View view)
{

    String localhost = "http://10.0.2.2/example/json/recent_notification.php";
    new ReadJSONFeedTask().execute(localhost);

    if(check != 0)
    {
        Intent i = new Intent(HomeScreen.this, NotificationPanel.class);
        i.putExtra("items", items);
        i.putExtra("short_items", short_items);
        startActivity(i);
    }
    else
    {
        Toast.makeText(getBaseContext(), "Either there is no notification to display or there might be a problem with your internet connection.", Toast.LENGTH_SHORT).show();
    }
}
}

int check是我检查服务器是否返回任何JSON数据的地方。如果check不为0,则不会切换到下一个activity
但此代码的问题是,当我点击按钮时,它会显示TOAST {{1}甚至在它从服务器中提取数据之前,它就永远不会进入下一个活动Either there is no notification to display or there might be a problem with your internet connection.。我理解这是由于NotificationPanel.class。更奇怪的是,如果我多次单击该按钮,应用程序会突然切换到显示AsyncTask中数据的下一个活动。但它并不总是奏效。是否有解决这个问题的方法?
请帮忙。
提前谢谢你。

2 个答案:

答案 0 :(得分:0)

使用if else将代码移动到onPostExecute中的最后一个。检查结果时,AsyncTask仍处于执行状态。

答案 1 :(得分:0)

您应该将这段代码放在onPostExecute方法中:

if(check != 0)
{
    Intent i = new Intent(HomeScreen.this, NotificationPanel.class);
    i.putExtra("items", items);
    i.putExtra("short_items", short_items);
    startActivity(i);
}
else
{
    Toast.makeText(getBaseContext(), "Either there is no notification to display or there might be a problem with your internet connection.", Toast.LENGTH_SHORT).show();
}

将它们放在当前代码之后,告诉我它是否有效。

&#34;更奇怪的是,如果我多次单击该按钮,应用程序会突然切换到下一个显示ListView中数据的活动。但它并不总是奏效。是否有解决这个问题的方法?&#34;

你在这里说的很清楚。一开始你不能运行你的意图,因为当你先点击几次按钮时,json还没有被提取。但是如果你继续点击它,它最终将获取JSON并能够进入下一个活动。

所以,我确定我所说的是需要做的事情。

修改 我确定你的异步任务应该是这样的:

private class ReadJSONFeedTask extends AsyncTask<Void, Void, Void>
{
@Override
protected void onPreExecute()
{
    super.onPreExecute();
    dialog = new ProgressDialog(HomeScreen.this);
    dialog.setMessage("Downloading Notifications. Please wait . . .");
    dialog.setIndeterminate(false);
    dialog.setCancelable(false);
    dialog.show();
}
 //no need a return statment
@Override
protected Void doInBackground(Void... params)
{

    try
    {
        JSONArray jsonArray = new JSONArray(readJSONFeed(urls[0]));
        items = new String[jsonArray.length()];
        short_items = new String[jsonArray.length()];
        for(int i = 0; i < jsonArray.length(); i++)
        {
            JSONObject jobj = jsonArray.getJSONObject(i);
            message3 = "SUBJECT : " + jobj.getString("subject") + "\n\n" + 
                    "DATE : " + jobj.getString("date") + "\n" + jobj.getString("time") + "\n\n"
                     + "NOTICE : " + jobj.getString("notice");
            message_short = "SUBJECT : " + jobj.getString("subject") + "\n" 
                    + "NOTICE : " + jobj.getString("notice").substring(0, 20) + "..."
                    + "\n" + jobj.getString("time");
            items[i] = message3;
            short_items[i] = message_short;

            check += 1;
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
@Override
protected void onPostExecute(String result)
{




    if(check != 0)
     {
       Intent i = new Intent(HomeScreen.this, NotificationPanel.class);
       i.putExtra("items", items);
       i.putExtra("short_items", short_items);
       startActivity(i);
     }
    else
     {
     Toast.makeText(getBaseContext(), "Either there is no notification to display or there might be a problem with your internet connection.", Toast.LENGTH_SHORT).show();
}

dialog.dismiss();
}
}