Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/215.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android AsyncTask和JSONParser中的ListView_Android_Json_Android Asynctask - Fatal编程技术网

Android AsyncTask和JSONParser中的ListView

Android AsyncTask和JSONParser中的ListView,android,json,android-asynctask,Android,Json,Android Asynctask,我将在我的服务器上从json获取新闻 我还有一个菜单按钮,可以刷新我的列表视图 我不知道我错在哪里 JSON文件(http://10.0.2.2:8020/test/index.php) JSONParser.java package com.example.myapp.library; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.In

我将在我的服务器上从json获取新闻

我还有一个菜单按钮,可以刷新我的列表视图

我不知道我错在哪里

JSON文件
(http://10.0.2.2:8020/test/index.php)

JSONParser.java

package com.example.myapp.library;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public JSONParser() {}

public JSONObject getJSONFromUrl(String url)
{
    /**
     * Making Http Request
     */
    try
    {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    }
    catch(UnsupportedEncodingException e)
    {
        e.printStackTrace();
    }
    catch(ClientProtocolException e)
    {
        e.printStackTrace();
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    /**
     * JSON retreive value 
     */
    try
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while((line = reader.readLine())!= null)
        {
            sb.append(line + "n");
        }
        is.close();
        json = sb.toString();
    }
    catch(Exception e)
    { e.printStackTrace(); }
    /**
     * Parse the String to JSON OBJECT 
     */
    try
    {   jObj = new JSONObject(json);  }
    catch (JSONException e)
    {   e.printStackTrace();    }
    /**
     * Return JSON Object
     */
    return jObj;    
}
}
package com.example.myapp.library;

import com.example.myapp.adapter.NewsListAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.Toast;

public class RefreshNews extends AsyncTask<Void,Void,Void> {

private String url;
private ListView listView;
private Activity context;
/////////////////////////
private JSONParser jsonParser;
private JSONObject jObj;
private NewsListAdapter myAdapter;
private ProgressDialog pDialog;
//////////////////////////////////
private static final String TAG_NEWS = "news";
private static final String TAG_TITLE = "title";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_CREATED_AT = "created_at";
////////////////////////////////////////////////////////////
private String[] title;
private String[] description;
private String[] created_at;


/**
 * Constructor
 **/
public RefreshNews(Activity context, ListView listView, String url)
{
    this.context = context;
    this.listView = listView;
    this.url = url;
}

@Override
protected void onPreExecute() {
    pDialog = new ProgressDialog(context);
    pDialog.setCancelable(false);
    pDialog.setMessage("Loading ...");
    pDialog.show();
    super.onPreExecute();
}

@Override
protected Void doInBackground(Void... arg0) {
    jsonParser = new JSONParser();
    jObj = jsonParser.getJSONFromUrl(url);
    try 
    {
        JSONArray News = jObj.getJSONArray(TAG_NEWS);
        for(int i=0; i<News.length(); i++)
        {
            JSONObject temp = News.getJSONObject(i);
            title[i] = temp.getString(TAG_TITLE);
            description[i] = temp.getString(TAG_DESCRIPTION);
            created_at[i] = temp.getString(TAG_CREATED_AT);
        }

    } 
    catch (JSONException e) 
    {
            Toast.makeText(context, "Error in doInBackground ...", 5000).show();
    }
    return null;
}

@Override
protected void onPostExecute(Void result) {
    myAdapter = new NewsListAdapter(context, title, description, created_at);
    listView.setAdapter(myAdapter);
    pDialog.dismiss();
    super.onPostExecute(result);
}

}
package com.example.myapp;

import com.example.myapp.library.RefreshNews;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

public class MainActivity extends Activity {

private static final String url = "http://10.0.2.2:8020/test/index.php";

ListView list;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    list = (ListView) findViewById(R.id.listView1);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId() == R.id.action_refresh)
    {
        RefreshNews refreshNews = new RefreshNews(MainActivity.this, list, url);
        refreshNews.execute();
    }
    return super.onOptionsItemSelected(item);
}

}
RefreshNews.java

package com.example.myapp.library;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public JSONParser() {}

public JSONObject getJSONFromUrl(String url)
{
    /**
     * Making Http Request
     */
    try
    {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    }
    catch(UnsupportedEncodingException e)
    {
        e.printStackTrace();
    }
    catch(ClientProtocolException e)
    {
        e.printStackTrace();
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    /**
     * JSON retreive value 
     */
    try
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while((line = reader.readLine())!= null)
        {
            sb.append(line + "n");
        }
        is.close();
        json = sb.toString();
    }
    catch(Exception e)
    { e.printStackTrace(); }
    /**
     * Parse the String to JSON OBJECT 
     */
    try
    {   jObj = new JSONObject(json);  }
    catch (JSONException e)
    {   e.printStackTrace();    }
    /**
     * Return JSON Object
     */
    return jObj;    
}
}
package com.example.myapp.library;

import com.example.myapp.adapter.NewsListAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.Toast;

public class RefreshNews extends AsyncTask<Void,Void,Void> {

private String url;
private ListView listView;
private Activity context;
/////////////////////////
private JSONParser jsonParser;
private JSONObject jObj;
private NewsListAdapter myAdapter;
private ProgressDialog pDialog;
//////////////////////////////////
private static final String TAG_NEWS = "news";
private static final String TAG_TITLE = "title";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_CREATED_AT = "created_at";
////////////////////////////////////////////////////////////
private String[] title;
private String[] description;
private String[] created_at;


/**
 * Constructor
 **/
public RefreshNews(Activity context, ListView listView, String url)
{
    this.context = context;
    this.listView = listView;
    this.url = url;
}

@Override
protected void onPreExecute() {
    pDialog = new ProgressDialog(context);
    pDialog.setCancelable(false);
    pDialog.setMessage("Loading ...");
    pDialog.show();
    super.onPreExecute();
}

@Override
protected Void doInBackground(Void... arg0) {
    jsonParser = new JSONParser();
    jObj = jsonParser.getJSONFromUrl(url);
    try 
    {
        JSONArray News = jObj.getJSONArray(TAG_NEWS);
        for(int i=0; i<News.length(); i++)
        {
            JSONObject temp = News.getJSONObject(i);
            title[i] = temp.getString(TAG_TITLE);
            description[i] = temp.getString(TAG_DESCRIPTION);
            created_at[i] = temp.getString(TAG_CREATED_AT);
        }

    } 
    catch (JSONException e) 
    {
            Toast.makeText(context, "Error in doInBackground ...", 5000).show();
    }
    return null;
}

@Override
protected void onPostExecute(Void result) {
    myAdapter = new NewsListAdapter(context, title, description, created_at);
    listView.setAdapter(myAdapter);
    pDialog.dismiss();
    super.onPostExecute(result);
}

}
package com.example.myapp;

import com.example.myapp.library.RefreshNews;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

public class MainActivity extends Activity {

private static final String url = "http://10.0.2.2:8020/test/index.php";

ListView list;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    list = (ListView) findViewById(R.id.listView1);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId() == R.id.action_refresh)
    {
        RefreshNews refreshNews = new RefreshNews(MainActivity.this, list, url);
        refreshNews.execute();
    }
    return super.onOptionsItemSelected(item);
}

}
Manifest.xml

<uses-permission android:name="android.permission.INTERNET"/>
更新:

10-19 04:34:15.215: W/System.err(13788): org.json.JSONException: Expected ':' after n at character 4 of {n  "news":n    [n      {"id":"1","title":"Number one","description":"This is First Message","created_at":"2014-04-04"},n       {"id":"2","title":"Number two","description":"This is Second Message","created_at":"2014-04-04"},n      {"id":"3","title":"Number three","description":"This is Third Message","created_at":"2014-04-04"}n  ]n}nn
看来我的JSON是错的。我编辑了我的JSONParser类:

sb.append(line + "n");   ---->    sb.append(line + "\n");
但是错误已经发生了

有什么建议吗

例外情况是:

10-19 04:34:15.215: W/System.err(13788): org.json.JSONException: Expected ':' after n at character 4 of {n  "news":n    [n      {"id":"1","title":"Number one","description":"This is First Message","created_at":"2014-04-04"},n       {"id":"2","title":"Number two","description":"This is Second Message","created_at":"2014-04-04"},n      {"id":"3","title":"Number three","description":"This is Third Message","created_at":"2014-04-04"}n  ]n}nn
(请下次扫描LogCat中的相关部分。并非所有内容。并将其添加到问题中)


JSON看起来正常,但错误显示JSON中有“
n
”字符。您的网站返回的信息不正确。我猜这些是“
\n
”?

我找到了一个解决我问题的教程。
这是它的

您收到的错误是什么?我重定向到eclipse。。。在调试窗口中:Thread[AsyncTask#1](Suspended(exception RuntimeException))ThreadPoolExecutor.runWorker(ThreadPoolExecuter$Worker)行:1098 ThreadPoolExecuter$Worker.run()行:573 Thread.run()行:856您能粘贴接收到的错误的完整堆栈跟踪吗?我已经在postTanks中添加了异常以供回答(并编辑我的问题)。我如何扫描LogCat中的相关部分?我不知道哪个部分显示了我的问题!!!另外,我如何修复此JSON错误?!我必须编辑我的JSON文件或Java代码?只需搜索“Exception”一词。您的php服务器返回JSON。这可能是罪魁祸首。我建议将此添加到您的问题中。