2017-05-31 24 views
0

ausgeführt Wie geht es dir?Json-Anwendung nur aus dem Android-Studio

Ich habe in den letzten Tagen meine neue jSon-Anwendung eingebaut. Es dauert params auf earthquak von dieser Website https://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php

Und es funktioniert super. aber nur wenn ich es aus dem google studio ausgeführt habe. Wenn ich dann die App schließe und sie manuell auf meinem Telefon öffne, sehe ich überhaupt keine Daten.

Ich meine die App öffnet, aber keine JSON-Daten. Nur leerer Bildschirm, weder textVIEW noch listView nothing.

Ich verwende Folgendes in der MainActivity.

package com.example.erang.jsonsample; 

import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.widget.ListView; 

import com.android.volley.Cache; 
import com.android.volley.Network; 
import com.android.volley.Request; 
import com.android.volley.RequestQueue; 
import com.android.volley.Response; 
import com.android.volley.VolleyError; 
import com.android.volley.toolbox.BasicNetwork; 
import com.android.volley.toolbox.DiskBasedCache; 
import com.android.volley.toolbox.HurlStack; 
import com.android.volley.toolbox.StringRequest; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.util.ArrayList; 

public class MainActivity extends AppCompatActivity { 

    ArrayList<Earthquake> earthquakes = new ArrayList<>(); 


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

     createJsonRequest(); 




     // Create an {@link EarthQukeAdapter}, whose data source is a list of {@link earthquake}s. The 
     // adapter knows how to create list items for each item in the list. 
     EarthQuakeAdapter adapter = new EarthQuakeAdapter(this, earthquakes); 

// Find the {@link ListView} object in the view hierarchy of the {@link Activity}. 
     // There should be a {@link ListView} with the view ID called list, which is declared in the 
     // earthquake_activity.xml layout file. 
     ListView listView = (ListView) findViewById(R.id.list); 

     // Make the {@link ListView} use the {@link WordAdapter} we created above, so that the 
     // {@link ListView} will display list items for each {@link earthquake} in the list. 
     listView.setAdapter(adapter); 

    } 

    @Override 
    protected void onStop() { 
     super.onStop(); 

    } 

    public void createJsonRequest() { 

// Instantiate the cache 
     Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap 

// Set up the network to use HttpURLConnection as the HTTP client. 
     Network network = new BasicNetwork(new HurlStack()); 

// Instantiate the RequestQueue with the cache and network. 
     RequestQueue mRequestQueue = new RequestQueue(cache, network); 

// Start the queue 
     mRequestQueue.start(); 

     String url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_month.geojson"; 

// Formulate the request and handle the response. 
     StringRequest stringRequest = new StringRequest(Request.Method.GET, url, 
       new Response.Listener<String>() { 
        @Override 
        public void onResponse(String response) { 
         //Passing the response 
         parseJsonRequest(response); 
        } 
       }, 
       new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 
         // Handle error 
        } 
       }); 

// Add the request to the RequestQueue. 
     mRequestQueue.add(stringRequest); 

    } 

    public void parseJsonRequest(String response) { 


     if (response != null) { 
      // Catch the exception so the app doesn't crash, and print the error message to the logs. 
      try { 
       JSONObject reader = new JSONObject(response); 
       JSONArray features = reader.getJSONArray("features"); 
       for(int index=0;index<features.length();index++){ 
        JSONObject properties = reader.getJSONArray("features").getJSONObject(index).getJSONObject("properties"); 
        Double magnitude = properties.getDouble("mag"); 
        String place = properties.getString("place"); 
        String url = properties.getString("url"); 
        //This split between offset location and primary location 
        String[] separated = place.split(","); 
         //If there is missing field jump to the next item 
         if(separated.length < 2){ 
          continue; 
         } 
         //This contain the offsetLocation 
         String offsetLocation = separated[0]; 
         //This contain the primaryLocation 
         separated[1] = separated[1].trim(); 
         String primaryLocation = separated[1]; 
        //Passing date twice one for the date and one for the time. 
        String updateDate = properties.getString("time"); 
        java.util.Date date=new java.util.Date(Long.valueOf(updateDate)); 
        //The second date passing the time 
        earthquakes.add(new Earthquake(magnitude, offsetLocation, primaryLocation, date, date, url)); 

       } 


      } catch (JSONException e) { 
       // If an error is thrown when executing any of the above statements in the "try" block, 
       // catch the exception here, so the app doesn't crash. Print a log message 
       // with the message from the exception. 
       Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e); 
      } 
     } 

    } 

} 

Wie Sie sehen können, verwende ich das folgende Volley-Paket für alle json Sachen. Weitere graben auf mein Telefon mit Catlog Ich sehe die folgende Zeile beim manuellen Öffnen der App.

Jede Idee, warum ich meine App läuft nur gut, wenn sie aus dem Android Studio ausgeführt wird.

In Manifestdatei Ich habe auch

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

Vielen Dank im voraus.

Eran

+0

Warum wäre es null? Zuerst bekomme ich keine Ausnahme. Zweitens bevölkere ich das Array auf dieser Linie Erdbeben.add (neues Erdbeben (Magnitude, OffsetLocation, primaryLocation, Datum, Datum, URL)); Warum funktioniert es großartig, wenn es vom Studio aus ausgeführt wird und sich bei der manuellen Ausführung unterscheidet? –

+0

Ich habe dich Frage bearbeitet, versuche dir vielleicht zu helfen. –

Antwort

0
public class MainActivity extends AppCompatActivity { 

ArrayList<Earthquake> earthquakes = new ArrayList<>(); 
EarthQuakeAdapter adapter; 
ListView listView; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    createJsonRequest(); 
    listView = (ListView) findViewById(R.id.list); 
} 

@Override 
protected void onStop() { 
    super.onStop(); 

} 

public void createJsonRequest() { 

// Instantiate the cache 
    Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap 

// Set up the network to use HttpURLConnection as the HTTP client. 
    Network network = new BasicNetwork(new HurlStack()); 

// Instantiate the RequestQueue with the cache and network. 
    RequestQueue mRequestQueue = new RequestQueue(cache, network); 

// Start the queue 
    mRequestQueue.start(); 

    String url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_month.geojson"; 

// Formulate the request and handle the response. 
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, 
      new Response.Listener<String>() { 
       @Override 
       public void onResponse(String response) { 
        //Passing the response 
        parseJsonRequest(response); 

        adapter = new EarthQuakeAdapter(MainActivity.this, earthquakes); 
        listView.setAdapter(adapter); 
       } 
      }, 
      new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 
        // Handle error 
       } 
      }); 

// Add the request to the RequestQueue. 
    mRequestQueue.add(stringRequest); 

} 

public void parseJsonRequest(String response) { 


    if (response != null) { 
     // Catch the exception so the app doesn't crash, and print the error message to the logs. 
     try { 
      JSONObject reader = new JSONObject(response); 
      JSONArray features = reader.getJSONArray("features"); 
      for(int index=0;index<features.length();index++){ 
       JSONObject properties = reader.getJSONArray("features").getJSONObject(index).getJSONObject("properties"); 
       Double magnitude = properties.getDouble("mag"); 
       String place = properties.getString("place"); 
       String url = properties.getString("url"); 
       //This split between offset location and primary location 
       String[] separated = place.split(","); 
       //If there is missing field jump to the next item 
       if(separated.length < 2){ 
        continue; 
       } 
       //This contain the offsetLocation 
       String offsetLocation = separated[0]; 
       //This contain the primaryLocation 
       separated[1] = separated[1].trim(); 
       String primaryLocation = separated[1]; 
       //Passing date twice one for the date and one for the time. 
       String updateDate = properties.getString("time"); 
       java.util.Date date=new java.util.Date(Long.valueOf(updateDate)); 
       //The second date passing the time 
       earthquakes.add(new Earthquake(magnitude, offsetLocation, primaryLocation, date, date, url)); 

      } 


     } catch (JSONException e) { 
      // If an error is thrown when executing any of the above statements in the "try" block, 
      // catch the exception here, so the app doesn't crash. Print a log message 
      // with the message from the exception. 
      Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e); 
     } 
    } 

} 

} 
+0

Ein Problem mit Ihrem Beispiel ist die listView.setAdapter (Adapter); Welche definieren in der OnCreate und es nicht in der OnResponse Recognize. Aber ich vermisse die Zeile der Erstellung des Arrays Sie entfernen es vollständig –

+0

sonst nur eine Sache, in Ihrem Code nach parseJsonRequest (Antwort); Füge diese Zeile hinzu adapter.notifyDataSetChanged(); –

+0

Hilft nicht ... aber danke für die Mühe Mohammad., :-) –

0

Ich konnte das Problem lösen. Zuerst suchte ich nach einer anderen Implementierung, die Async verwendete, und ich sah, dass es eine onPostExecute-Methode gibt, die nach der Ausführung ausgeführt wird. Als ich volley benutze, habe ich nach etwas ähnlichem gesucht. Und ich habe verstanden, dass ich OnResponse-Methode verwenden muss. Also habe ich meine 3 Codezeilen umgeschaltet.

@Override 
public void onResponse(String response) { 
//Passing the response 
parseJsonRequest(response); 

EarthQuakeAdapter adapter = new EarthQuakeAdapter(MainActivity.this, earthquakes); 

ListView listView = (ListView) findViewById(R.id.list); 

listView.setAdapter(adapter); 
    } 
}, 

In zum OnResponse so erst nach dem Array gefüllt wird ich den Adapter erstellen und in die Listenansicht hinzuzufügen.

Verwandte Themen