我遇到了无法解决的问题。我是Android开发的新手。我的应用包含一个列表视图,可通过JSON
获取请求从HTTP
文件中获取信息。
这部分没问题,它正在运作。但我不能设法对我的第二个活动做同样的事情,其中包括显示信息的布局。我打算用意图在视图之间传递信息。
即使列表视图活动正在运行,我也无法在第二个活动中使用相同的功能而不会发生崩溃。我想发一个HTTP
get请求并解析Json。
Bellow是列表视图活动&第二项活动。为了让这项工作我必须做些什么改变?
ListView活动:正常工作
public class ShopsActivity extends Activity {
private ProgressDialog pDialog;
// URL to get JSON
private static String url = "http://webserviceurl";
// JSON Node names
private static final String TAG_NAME = "shop_name";
private static final String TAG_ADDRESS_STRING = "shop_address";
private static final String TAG_URL = "shop_url";
private static final String TAG_BOOKLET_URL = "feuilletez";
TextView shop_address;
TextView shop_name;
TextView shop_url;
ImageButton feuilletez;
private ListView list;
private ImageButton button1;
private ImageButton button2;
private ImageButton button3;
private ImageButton button4;
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Portrait only
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_shops);
// Calling async task to get json
new GetJson().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetJson extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ShopsActivity.this);
pDialog.setMessage("Mise à jour...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
JSONArray array = null;
try {
array = new JSONArray(jsonStr);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
for (int i = 0; i <array.length(); i++){
JSONObject jsonObject = array.getJSONObject(i);
String id = jsonObject.getString("id");
System.out.println("id --->" + id);
String url = jsonObject.getString("url");
System.out.println("url --->" + url);
String created_at = jsonObject.getString("created_at");
System.out.println("created_at --->" + created_at);
String updated_at = jsonObject.getString("updated_at");
System.out.println("updated_at --->" + updated_at);
String name = jsonObject.getString("name");
System.out.println("name --->" + name);
JSONArray photos_urls = jsonObject.getJSONArray("photos_urls");
System.out.println("photos_urls --->" + photos_urls);
String address_string = jsonObject.getString("address_string");
System.out.println("address_string --->" + address_string);
JSONObject booklet = jsonObject.getJSONObject("booklet");
String id_booklet = booklet.getString("id");
System.out.println("id_booklet --->" + id_booklet);
String url_booklet = booklet.getString("url");
System.out.println("url_booklet --->" + url_booklet);
String created_at_booklet = booklet.getString("created_at");
System.out.println("created_at_booklet --->" + created_at_booklet);
String updated_at_booklet = booklet.getString("updated_at");
System.out.println("updated_at_booklet --->" + updated_at_booklet);
String document_url = booklet.getString("document_url");
System.out.println("document_url --->" + document_url);
String presented = booklet.getString("presented");
System.out.println("presented --->" + presented);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NAME, name);
map.put(TAG_ADDRESS_STRING, address_string);
map.put(TAG_URL, url);
map.put(TAG_BOOKLET_URL, url_booklet);
oslist.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
list = (ListView) findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(ShopsActivity.this, oslist,
R.layout.listview_item_row, new String[] { TAG_NAME,
TAG_ADDRESS_STRING, TAG_BOOKLET_URL }, new int[] { R.id.name_shop,
R.id.address_shop});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(ShopsActivity.this, ShopActivity.class);
// Toast.makeText(ShopsActivity.this, "You Clicked at "+oslist.get(+position).get("shop_url"), Toast.LENGTH_SHORT).show();
intent.putExtra("shopurl",oslist.get(+position).get("shop_url"));
overridePendingTransition(R.anim.animationin, R.anim.animationout);
startActivity(intent);
}
});
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
}
}
}
TargetActivity:尝试适应工作:
public class ShopActivity extends Activity {
private int userIcon, jewelleryIcon;
private GoogleMap theMap;
private LocationManager locMan;
private Marker userMarker;
private Marker bijouterie;
private Button emailButton;
private long latitude;
private long longitude;
private String image1;
private String image2;
private ImageButton button1;
private ImageButton button2;
private ImageButton button3;
private ImageButton button4;
private ImageButton button5;
private ImageButton catalogue;
private Button goToMap;
private String thebooketurl = null;
/** Called when the activity is first created.
* @return */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Portrait only
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_shop);
// View's main buttons
goToMap = (Button)findViewById(R.id.mapClick);
goToMap.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View goToMap) {
Intent intent = new Intent(ShopActivity.this, FullMapActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
}
});
button1 = (ImageButton)findViewById(R.id.imageButton1);
button1.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View Button1) {
finish();//go back to the previous Activity
overridePendingTransition(R.anim.backin, R.anim.backout);
}
});
button2 = (ImageButton)findViewById(R.id.imageButton2);
button2.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View Button1) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"mail.fr"});
i.putExtra(Intent.EXTRA_SUBJECT, "");
i.putExtra(Intent.EXTRA_TEXT , "");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(ShopActivity.this, "Pas de client de messagerie installé sur cet appareil.", Toast.LENGTH_SHORT).show();
}
}
});
button3 = (ImageButton)findViewById(R.id.imageButton3);
button3.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View Button1) {
Intent intent = new Intent(ShopActivity.this, PhilosophyActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.animationin, R.anim.animationout);
}
});
button4 = (ImageButton)findViewById(R.id.imageButton4);
button4.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View Button1) {
finish();//go back to the previous Activity
overridePendingTransition(R.anim.backin, R.anim.backout);
}
});
button5 = (ImageButton)findViewById(R.id.imageButton6);
button5.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View Button1) {
Intent intent = new Intent(ShopActivity.this, MapActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.animationin, R.anim.animationout);
}
});
catalogue = (ImageButton)findViewById(R.id.feuilletez);
catalogue.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View Button1) {
Intent bookleturl = new Intent(ShopActivity.this, PdfReader.class);
bookleturl.putExtra("bookleturl", thebooketurl);
startActivity(bookleturl);
Intent intent = new Intent(ShopActivity.this, PdfReader.class);
startActivity(intent);
overridePendingTransition(R.anim.animationin, R.anim.animationout);
}
});
// Add fonts
// Typeface typeFace=Typeface.createFromAsset(getAssets(),"fonts/HelveticaNeueBold.ttf");
// View's items
TextView shopAddressTextView=(TextView) findViewById(R.id.shopAddress);
// shopAddressTextView.setTypeface(typeFace);
TextView shopNameTextView=(TextView) findViewById(R.id.shopName);
TextView shopPhoneTextView=(TextView) findViewById(R.id.shopPhone);
TextView shopFaxTextView=(TextView) findViewById(R.id.shopFax);
TextView shopHoursTextView=(TextView) findViewById(R.id.shopHours);
TextView shopHoursTextView2=(TextView) findViewById(R.id.shopHours2);
ImageView firstImage=(ImageView) findViewById(R.id.firstImage);
ImageView secondImage=(ImageView) findViewById(R.id.secondImage);
// HTTP Request
AsyncHttpClient client = new AsyncHttpClient();
client.get("webserviceurl", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
System.out.println("this is reponse >" + response);
}
});
// Reading text file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"test.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
String myjsonstring = sb.toString();
Log.d("string: " , myjsonstring);
JSONArray array = null;
try {
array = new JSONArray(myjsonstring);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
JSONObject jsonObject = array.getJSONObject(0);
String id = jsonObject.getString("id");
System.out.println("id --->" + id);
String url = jsonObject.getString("url");
System.out.println("url --->" + url);
String created_at = jsonObject.getString("created_at");
System.out.println("created_at --->" + created_at);
String updated_at = jsonObject.getString("updated_at");
System.out.println("updated_at --->" + updated_at);
String name = jsonObject.getString("name");
shopNameTextView.setText(jsonObject.getString("name"));
System.out.println("name --->" + name);
String phone = jsonObject.getString("phone");
if(phone == "null")
shopPhoneTextView.setText("-");
else
shopPhoneTextView.setText(jsonObject.getString("phone"));
System.out.println("phone --->" + phone);
String fax = jsonObject.getString("fax");
if(fax == "null")
shopFaxTextView.setText("-");
else
shopFaxTextView.setText(jsonObject.getString("fax"));
System.out.println("fax --->" + fax);
final String email = jsonObject.getString("email");
emailButton = (Button)findViewById(R.id.buttonEmail);
emailButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View Button4) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
if(email == "null")
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"mail.fr"});
else
i.putExtra(Intent.EXTRA_EMAIL , new String[]{email});
i.putExtra(Intent.EXTRA_SUBJECT, "");
i.putExtra(Intent.EXTRA_TEXT , "");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(ShopActivity.this, "Pas de client de messagerie installé sur cet appareil.", Toast.LENGTH_SHORT).show();
}
}
});
//shopEmailTextView.setText(jsonObject.getString("email"));
System.out.println("email --->" + phone);
String website_url = jsonObject.getString("website_url");
System.out.println("website_url --->" + phone);
String detail = jsonObject.getString("detail");
System.out.println("detail --->" + detail);
String logo_url = jsonObject.getString("logo_url");
System.out.println("logo_url --->" + logo_url);
String logo_thumbnail_url = jsonObject.getString("logo_thumbnail_url");
System.out.println("logo_thumbnail_url --->" + logo_thumbnail_url);
JSONArray photos_urls = jsonObject.getJSONArray("photos_urls");
System.out.println("photos_urls --->" + photos_urls);
image1 = photos_urls.getString(0);
if(image1 != null){
new DownloadImageTask((ImageView) findViewById(R.id.firstImage))
.execute(image1);
}
image2 = photos_urls.getString(0);
if(image2 != null){
new DownloadImageTask((ImageView) findViewById(R.id.secondImage))
.execute(image2);
}
JSONArray opening_hours = jsonObject.getJSONArray("opening_hours");
String hoursTitle = "Horaires d'ouverture :";
String lundi = opening_hours.getString(0);
if(lundi==null)
lundi = "NC";
String mardi = opening_hours.getString(1);
String mercredi = opening_hours.getString(2);
String jeudi = opening_hours.getString(3);
String vendredi = opening_hours.getString(4);
String samedi = opening_hours.getString(5);
shopHoursTextView.setText(hoursTitle+"\nLundi : "+lundi+"\nMardi : "+mardi+"\nMercredi : "+mercredi+"");
shopHoursTextView2.setText("Jeudi : "+jeudi+"\nVendredi : "+vendredi+"\nSamedi : "+samedi);
System.out.println("opening_hours --->" + opening_hours);
String address_string = jsonObject.getString("address_string");
shopAddressTextView.setText(jsonObject.getString("address_string"));
System.out.println("address_string --->" + address_string);
JSONObject contact = jsonObject.getJSONObject("contact");
String title = contact.getString("title");
System.out.println("title --->" + title);
String first_name = contact.getString("first_name");
System.out.println("first_name --->" + first_name);
String last_name = contact.getString("last_name");
System.out.println("last_name --->" + last_name);
JSONObject address = jsonObject.getJSONObject("address");
String id_address = address.getString("id");
System.out.println("id --->" + id_address);
String url_address = address.getString("url");
System.out.println("url --->" + url_address);
String created_at_address = address.getString("created_at");
System.out.println("created_at_address --->" + created_at_address);
String updated_at_address = address.getString("updated_at");
System.out.println("updated_at_address --->" + updated_at_address);
String street_address = address.getString("street_address");
System.out.println("street_address --->" + street_address);
String extended_address = address.getString("extended_address");
System.out.println("extended_address --->" + extended_address);
String postal_code = address.getString("postal_code");
System.out.println("postal_code --->" + postal_code);
String locality = address.getString("locality");
System.out.println("locality --->" + locality);
String country_code_alpha2 = address.getString("country_code_alpha2");
System.out.println("country_code_alpha2 --->" + country_code_alpha2);
JSONArray coordinates = address.getJSONArray("coordinates");
System.out.println("coordinates --->" + coordinates);
latitude = coordinates.getLong(0);
longitude = coordinates.getLong(1);
JSONObject booklet = jsonObject.getJSONObject("booklet");
String id_booklet = booklet.getString("id");
System.out.println("id_booklet --->" + id_booklet);
String url_booklet = booklet.getString("url");
System.out.println("url_booklet --->" + url_booklet);
String created_at_booklet = booklet.getString("created_at");
System.out.println("created_at_booklet --->" + created_at_booklet);
String updated_at_booklet = booklet.getString("updated_at");
System.out.println("updated_at_booklet --->" + updated_at_booklet);
String title_booklet = booklet.getString("title");
System.out.println("title_booklet --->" + title_booklet);
String thumbnail_url = booklet.getString("thumbnail_url");
System.out.println("thumbnail_url --->" + thumbnail_url);
String document_url = booklet.getString("document_url");
System.out.println("document_url --->" + document_url);
String presented = booklet.getString("presented");
thebooketurl = presented;
System.out.println("presented --->" + presented);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Check status of Google Play Services
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
// Check Google Play Service Available
try {
if (status != ConnectionResult.SUCCESS) {
}
} catch (Exception e) {
Log.e("Error: GooglePlayServiceUtil: ", "" + e);
}
// Google Maps
userIcon = R.drawable.blue_point;
jewelleryIcon = R.drawable.pointeur;
if(theMap==null){
//map not instantiated yet
}
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
if(theMap != null){
//ok - proceed
}
theMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Map
LatLng BIJOUTERIE = new LatLng(latitude, longitude);
bijouterie = theMap.addMarker(new MarkerOptions()
.position(BIJOUTERIE)
.title("title")
.icon(BitmapDescriptorFactory.fromResource(jewelleryIcon))
.snippet("address"));
theMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 7.5f), 4000, null);
}
@Override
public void onBackPressed() {
finish();//go back to the previous Activity
overridePendingTransition(R.anim.backin, R.anim.backout);
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap myImage = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
myImage = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
myImage = Bitmap.createScaledBitmap(myImage, 300, 200, false);;
return myImage;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
public String replaceNull(String input){
return ((input== null) ? "-" : input);
}
}
}