我从url获取Json文件,并希望逐节点地显示json文件中的数据,然后将数据保存到DATABASE中。我使用以下代码但不工作请帮助我找到错误。我已经在清单文件中提到了互联网权限。我也在添加我的LOGCAT。感谢。
我的主要活动:
public class MainActivity extends Activity {
String url="maps.google.com/maps/api/geocode/json?latlng="+31.5279024+","+74.3495554;
JSONArray user = null;
private static final String TAG_USER = "results";
private static final String TAG_address = "address_components" ;
private static final String TAG_addressLName = "long_name";
private static final String TAG_addressSName= "short_name" ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating new JSON Parser
JsonParser jParser = new JsonParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString(TAG_address );
String name = c.getString(TAG_addressLName );
String email = c.getString( TAG_addressSName);
//Importing TextView
final TextView uid = (TextView)findViewById(R.id.uid);
final TextView name1 = (TextView)findViewById(R.id.name1);
final TextView email1 = (TextView)findViewById(R.id.email);
//Set JSON Data in TextView
uid.setText(id);
name1.setText(name);
email1.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
@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) {
// 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
我的JSON课程
包com.parsep.parse;
public class JsonParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JsonParser (){
}
public JSONObject getJSONFromUrl(String url )
{
try
{
DefaultHttpClient httpClient= new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
// httpPost.setEntity(new UrlEncodedFormEntity(params));
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();
}
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();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
我的LOGCAT:
11-05 14:45:29.790: E/AndroidRuntime(533): FATAL EXCEPTION: main
11-05 14:45:29.790: E/AndroidRuntime(533): java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.parsep.parse/com.parsep.parse.MainActivity}: java.lang.IllegalStateException:
Target host must not be null, or set in parameters. scheme=null, host=null, path=maps.google.com/maps/api/geocode/json
11-05 14:45:29.790: E/AndroidRuntime(533): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
11-05 14:45:29.790: E/AndroidRuntime(533): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
11-05 14:45:29.790: E/AndroidRuntime(533): at android.app.ActivityThread.access$600(ActivityThread.java:123)
11-05 14:45:29.790: E/AndroidRuntime(533): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
11-05 14:45:29.790: E/AndroidRuntime(533): at android.os.Handler.dispatchMessage(Handler.java:99)
11-05 14:45:29.790: E/AndroidRuntime(533): at android.os.Looper.loop(Looper.java:137)
11-05 14:45:29.790: E/AndroidRuntime(533): at android.app.ActivityThread.main(ActivityThread.java:4424)
11-05 14:45:29.790: E/AndroidRuntime(533): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 14:45:29.790: E/AndroidRuntime(533): at java.lang.reflect.Method.invoke(Method.java:511)
11-05 14:45:29.790: E/AndroidRuntime(533): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-05 14:45:29.790: E/AndroidRuntime(533): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-05 14:45:29.790: E/AndroidRuntime(533): at dalvik.system.NativeStart.main(Native Method)
11-05 14:45:29.790: E/AndroidRuntime(533): Caused by: java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=maps.google.com/maps/api/geocode/json
11-05 14:45:29.790: E/AndroidRuntime(533): at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:591)
11-05 14:45:29.790: E/AndroidRuntime(533): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293)
11-05 14:45:29.790: E/AndroidRuntime(533): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-05 14:45:29.790: E/AndroidRuntime(533): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-05 14:45:29.790: E/AndroidRuntime(533): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-05 14:45:29.790: E/AndroidRuntime(533): at com.parsep.parse.JsonParser.getJSONFromUrl(JsonParser.java:40)
11-05 14:45:29.790: E/AndroidRuntime(533): at com.parsep.parse.MainActivity.onCreate(MainActivity.java:29)
11-05 14:45:29.790: E/AndroidRuntime(533): at android.app.Activity.performCreate(Activity.java:4465)
11-05 14:45:29.790: E/AndroidRuntime(533): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
11-05 14:45:29.790: E/AndroidRuntime(533): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
11-05 14:45:29.790: E/AndroidRuntime(533): ... 11 more
11-05 14:45:30.010: I/dalvikvm(533): threadid=3: reacting to signal 3
11-05 14:45:30.049: I/dalvikvm(533): Wrote stack traces to '/data/anr/traces.txt'
11-05 14:45:30.350: I/dalvikvm(533): threadid=3: reacting to signal 3
11-05 14:45:30.360: I/dalvikvm(533): Wrote stack traces to '/data/anr/traces.txt'
答案 0 :(得分:1)
只需用您的代码替换以下行。这可能会有所帮助
public class MainActivity extends Activity {
String url="http://maps.google.com/maps/api/geocode/json?latlng="+31.5279024+","+74.3495554";
JSONArray user = null;
答案 1 :(得分:0)
我想你必须添加" http://"到你的网址让它运作。
答案 2 :(得分:0)
尝试这种方式:
new AsyncTaskParseJson().execute(); // write this in onCreate(); method.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://maps.google.com/maps/api/geocode/json?latlng="+31.5279024+","+74.3495554;;
// contacts JSONArray
JSONArray dataJsonArr = null;
@Override
protected void onPreExecute() {}
@Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
//Below parsing is just for your reference, do your task here.
// get the array of users
dataJsonArr = json.getJSONArray("Users");
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String firstname = c.getString("firstname");
String lastname = c.getString("lastname");
String username = c.getString("username");
// show the values in our logcat
Log.e(TAG, "firstname: " + firstname
+ ", lastname: " + lastname
+ ", username: " + username);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String strFromDoInBg) {}
}
}
答案 3 :(得分:0)
如果您只想要lat-long的地址列表,请使用反向地理编码。
以这种方式调用以下方法并获取数据。
Address address=getAddressListFromLatLong(YOUR LATITUDE, YOUR LONGITUDE);
String country=address.getCountryName();
String address1=address.getAddressLine(1);
Strin address2=address.getAddressLine(2);
String postalCode=address.getPostalCode();
public static List<Address> getAddressListFromLatLong(double lat, double lng) {
geocoder = new Geocoder(YOUR ACTIVITY.this);
List<Address> list = null;
try {
list = geocoder.getFromLocation(lat, lng, 10); //10 is for results, you can use 1 if you want 1 result only.
} catch (Throwable e) {
e.printStackTrace();
}
return list;
}