2016-07-07 8 views
-1

Ich bin wirklich neu in Android-Anwendung Erstellung und ich verwende Android Studio, um an meinem Projekt zu arbeiten. Ich hole Json-Ergebnis von meiner DB und das geholte Ergebnis bin, was ich will, aber ich weiß nicht, wie man asynctask vor onCreate beenden lässt. Meine ListView ist leer, aber ich habe mit dem Debugger bestätigt, dass meine Asynctask-Ergebniswerte existieren.Android Async-Ausführung kommt nach onCreate

aktualisiert: Ich Spuren Fehler hier:

public void populatedata(){ 
      /**get back result from pref**/ 
      SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
      String result =pref.getString("result", "null"); 
     try{ 
      Log.d("ADebugTag", "Value: "+result); 

      JSONObject person = new JSONObject(result); 
      JSONArray jsonMainNode = person.getJSONArray("result"); 
      final int n = jsonMainNode.length(); 

      ListView lv= (ListView)findViewById(R.id.listView1); 
      String[] from = new String[] {"id", "time"}; 
      int[] to = new int[] {android.R.id.text1}; 

      List<Map<String,String>> classList = new ArrayList<Map<String,String>>(); 

     // for(int i = 0; i< n; i++){ 
        //HashMap<String, String> map = new HashMap<String, String>(); 
     //  JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); 

      //  String id = jsonChildNode.getString("id"); 
      //  String schedule = jsonChildNode.getString("schedule"); 
      //  String time = jsonChildNode.getString("time"); 
      // String output = schedule + time; 
       // classList.add(createchild(id,output)); 
       // Log.d("ADebugTag", "Value before loop: "+classList); 
      // } 
      // Log.d("ADebugTag", "Value after loop: "+classList); 
      Log.d("ADebugTag", "Hi, Im here5"); 


      for(int i = 0; i < 10; i++){ 
       HashMap<String, String> map = new HashMap<String, String>(); 

       map.put("id", "time" + i); 
       map.put("col_1", "col_1_item_" + i); 
       map.put("col_2", "col_2_item_" + i); 
       map.put("col_3", "col_3_item_" + i); 
       classList.add(map); 
      } 

      SimpleAdapter simpleAdapter = new SimpleAdapter(this,classList, android.R.layout.simple_list_item_1, from, to); 
      lv.setAdapter(simpleAdapter); 

     } 
     catch(JSONException e){ 
      Toast.makeText(getApplicationContext(), "Error"+e.toString(), Toast.LENGTH_SHORT).show(); 
     } 

    } 

    private HashMap<String, String>createchild(String id,String output){ 
     HashMap<String,String> childNo = new HashMap<String,String>(); 

     childNo.put(id,output); 
     Log.d("ADebugTag", "Hi, Im here4"); 
     return childNo; 

    } 

the // for loop is the one i wanna work it out, and my string result `is{"result":[{"id":"00000000001","schedule":"000001","time":"10:21:37"}]}` 


updated: It's my mistake, I did not create a R.layout and textview for it, I learned to use custom adapter and create an external layout. 

public class ViewClassActivity extends AppCompatActivity{ 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_view_class); 

     /**prepare list**/ 
     SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
     String id =pref.getString("userid", "null"); 



     Log.d("ADebugTag", "Hi, Im here"); 
     new fetchclass(this,id).execute(id); 


     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 
     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 

     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 


    } 

    public void getdata(String result){ 
     //save preferences 
     SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
     SharedPreferences.Editor editor = pref.edit(); 

     editor.putString("result", result); // Saving result string 

     Log.d("ADebugTag", "Hi, Im here3"); 
     // Save the changes in SharedPreferences 
     editor.apply(); // apply changes 
     populatedata(); 

     Log.d("ADebugTag", "Hi, Im here6"); 
    } 

    public void populatedata(){ 
     /**get back result from pref**/ 
     SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
     String result =pref.getString("result", "null"); 
     Log.d("ADebugTag",result); 

     try{ 
      Log.d("ADebugTag", "Value: "+result); 

      JSONObject person = new JSONObject(result); 
      JSONArray jsonMainNode = person.getJSONArray("result"); 
      final int n = jsonMainNode.length(); 

      ListView lv= (ListView)findViewById(R.id.listView1); 
      String[] from = new String[] {"id", "schedule"}; 
      int[] to = new int[] {R.id.textView20,R.id.textView21}; 

      //List<Map<String,String>> classList = new ArrayList<Map<String,String>>(); 
      ArrayList<HashMap<String,String>> classList = new ArrayList<>(); 

      for(int i = 0; i< n; i++){ 
       HashMap<String, String> hashMap = new HashMap<>(); 
       JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); 

       String id = jsonChildNode.getString("id"); 
       String schedule = jsonChildNode.getString("schedule"); 
       String time = jsonChildNode.getString("time"); 
       String output = schedule + time; 

       hashMap.put("id", id); 
       hashMap.put("schedule", output); 

       classList.add(hashMap); 
       //classList.add(createchild(id,output)); 
       Log.d("ADebugTag", "Value before loop: "+classList); 
      } 

      CustomAdapter simpleAdapter = new CustomAdapter(this,classList, R.layout.list_view_item, from, to); 
      lv.setAdapter(simpleAdapter); 

     } 
     catch(JSONException e){ 
      Toast.makeText(getApplicationContext(), "Error"+e.toString(), Toast.LENGTH_SHORT).show(); 
     } 

    } 

    private HashMap<String, String>createchild(String id,String output){ 
     HashMap<String,String> childNo = new HashMap<String,String>(); 

     childNo.put(id,output); 
     Log.d("ADebugTag", "Hi, Im here4"); 
     return childNo; 

    } 

list_view_item.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin"> 

     <TextView 
      android:id="@+id/textView20" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      android:padding="@dimen/activity_horizontal_margin" 
      android:text="Demo1" 
      android:textColor="#000" /> 

     <TextView 
      android:id="@+id/textView21" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      android:padding="@dimen/activity_horizontal_margin" 
      android:text="Demo2" 
      android:textColor="#000" 
      android:layout_alignParentTop="true" 
      android:layout_toRightOf="@+id/textView20" 
      android:layout_toEndOf="@+id/textView20" /> 

</RelativeLayout> 

kundenspezifische Adapter

public class CustomAdapter extends SimpleAdapter { 
    LayoutInflater inflater; 
    Context context; 
    ArrayList<HashMap<String, String>> arrayList; 

    public CustomAdapter(Context context, ArrayList<HashMap<String, String>> data, int resource, String[] from, int[] to) { 
     super(context, data, resource, from, to); 
     this.context = context; 
     this.arrayList = data; 
     inflater.from(context); 
    } 



} 

dachte mein Problem aus dieser Seite, und danke für jedermann für die Hilfe:

custom-listview

+0

Denn wenn Asynchron ausgeführt Hintergrund-Thread (post Ergebnis mit onPost()) und das Programm bewegt sich zur nächsten Zeile gestartet wird ... und wie ich Ihre Listenansicht mit bevölkert sehen Adapter noch vor Hintergrund Task in abgeschlossen ... eine Lösung, die ich segge wäre Adapter zu setzen, nachdem Ihre Aufgabe beendet ist dh Aufruf 'SimpleAdapter simpleAdapter = new SimpleAdapter (this, classList, android.R.layout.simple_list_item_1, new String [] { "Ergebnis"}, new int [] {android.R.id.text1}); listView.setAdapter (simpleAdapter); 'nach' bevllededata(); 'in Ihrer' getdata (String Ergebnis) 'und überprüfen Sie die Ergebnisse – Mohit

+0

@Mohit Ihre Arbeit vorschlagen! mein Debugger zeigt mir jetzt, dass Code die gewünschte Sequenz ausführt! aber mir steht immer noch eine leere listeansicht bevor! Könnte es der Grund für die generierte Hasmap sein? der String-Wert, den ich erhalte, ist ** {"result": [{"id": "00000000001", "Zeitplan": "000001", "time": "10:21:37"}]} ** aber nach hasmap ist es ** [{00000000001 = 00000110: 21: 37}] ** und btw posten Sie Ihre Antwort unten, so kann ich es als ein Häkchen markieren, lösen Sie die grundlegendste meiner Frage, obwohl meine Listenansicht immer noch leer –

+0

* Erstens: * bitte update Code so ist es bequem zu analysieren .............. * Zweitens: * Ja, Sie haben Recht, jedes Mal, wenn Sie 'createchild()' in Schleife Sie anrufen initialisiere hashmap und du bekommst neue leere hashmap..just deklariere globale hashmap variable und initialisiere sie einmal (sprich bei onCreate() oder einigen wo aber nicht in loop) und rufe sie in method ... hoffe es hilft – Mohit

Antwort

0

Sie können die asynchrone Task nicht vor onCreate beenden lassen. Das ist der ganze Sinn einer asynchronen Task - sie wird parallel ausgeführt. Stattdessen sollten Sie einen Ladebildschirm (auch nur so etwas wie einen unbestimmten Fortschrittsbalken) aufstellen, um dem Benutzer zu zeigen, dass Sie auf Daten warten, und dann die Daten in die Liste in onPostExecute der Aufgabe laden.

+0

Es wird Ihr Leben viel einfacher, wenn Sie einen Event-Bus verwenden, um mit asynchronen Aufgaben arbeiten. http://simonvt.net/2014/04/17/asynctask-is-bad-and-you-should-feel-bad/ – Chamindu

+0

Verwenden Sie keinen Event-Bus für asynchrone Aufgaben. Das bringt nur schrecklichen Spaghetti-Code mit sich. Wenn Sie jemals einen Event-Bus verwenden müssen, bedeutet dies, dass Sie Ihren Code vollständig im Middle-Design erstellt haben. –

+0

Warum ist ein Event-Bus eine schlechte Sache? – Chamindu

0

Try unten Code:

public class ViewClassActivity extends AppCompatActivity{ 


List<Map<String,String>> classList = new ArrayList<Map<String,String>>(); 

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_view_class); 

    /**prepare list**/ 
    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
    String id =pref.getString("userid", "null"); 

    ListView listView = (ListView) findViewById(R.id.listView1); 
    SimpleAdapter simpleAdapter = new SimpleAdapter(this,classList, android.R.layout.simple_list_item_1, new String[] {"result"}, new int[] {android.R.id.text1}); 
    listView.setAdapter(simpleAdapter); 

    Log.d("ADebugTag", "Hi, Im here5"); 

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 

    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 


    Log.d("ADebugTag", "Hi, Im here"); 
    new fetchclass(this,id).execute(id); 
} 

private HashMap<String, String>createchild(String id,String output){ 
    HashMap<String,String> childNo = new HashMap<String,String>(); 
    childNo.put(id,output); 
    Log.d("ADebugTag", "Hi, Im here4"); 
    return childNo; 

} 

public class fetchclass extends AsyncTask<String,String,String>{ 

ProgressDialog proDialog; 
String userid; 

public ViewClassActivity activity; 


public fetchclass(ViewClassActivity a, String id) { 

    this.activity = a; 
    this.userid = id; 
} 

protected void onPreExecute(){ 
    //pre-execute procedure 
    // Showing progress loading dialog 
    proDialog = new ProgressDialog(activity); 
    proDialog.setMessage("Loading..."); 
    proDialog.setCancelable(false); 
    proDialog.show(); 
} 

@Override 
protected String doInBackground(String... arg0) { 
    try{ 
     String id = arg0[0]; 

     String link="http://www.commcreative.me/mnas/attendance.php"; 
     String data = URLEncoder.encode("id", "UTF-8") + "=" + URLEncoder.encode(id, "UTF-8"); 

     URL url = new URL(link); 
     URLConnection conn = url.openConnection(); 

     conn.setDoOutput(true); 
     OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 

     wr.write(data); 
     wr.flush(); 

     BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 

     StringBuilder sb = new StringBuilder(); 
     String line = null; 

     // Read Server Response 
     while((line = reader.readLine()) != null) 
     { 
      sb.append(line); 
      break; 
     } 

     try{ 
      Log.d("ADebugTag", "Value: "+sb.toString();); 

      JSONObject person = new JSONObject(sb.toString();); 
      JSONArray jsonMainNode = person.getJSONArray("result"); 
      final int n = jsonMainNode.length(); 

      for(int i = 0; i<n;i++){ 
       JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); 

       String id = jsonChildNode.getString("id"); 
       String schedule = jsonChildNode.getString("schedule"); 
       String time = jsonChildNode.getString("time"); 
       String output = schedule + time; 
       classList.add(createchild(id,output)); 
       Log.d("ADebugTag", "Value: "+classList); 
      } 

      simpleAdapter .notifyDataSetChange(); 

     } 
     catch(JSONException e){ 
      Toast.makeText(getApplicationContext(), "Error"+e.toString(), Toast.LENGTH_SHORT).show(); 
     } 

     return sb.toString(); 
    } 
    catch(Exception e){ 
     return new String("Exception: " + e.getMessage()); 
    } 
} 


@Override 
protected void onPostExecute(String result){ 

    // Dismiss the progress dialog 
    if (proDialog.isShowing()) 
     proDialog.dismiss(); 
    //dismiss end 

    // Log.d("ADebugTag", "Hi, Im here2"); 
    // activity.getdata(result); 

} 
} 

private HashMap<String, String>createchild(String id,String output){ 
    HashMap<String,String> childNo = new HashMap<String,String>(); 
    childNo.put(id,output); 
    Log.d("ADebugTag", "Hi, Im here4"); 
    return childNo; 

} 



} 
+0

gibt es viele Fehler in fetchdata Klasse zB: 'code'Log.d ("ADebugTag", "Wert:" + sb.toString();); JSONObject person = neues JSONObject (sb.toString();); 'code' die; Unerwartetes Token, und die SimpleAdapter-Methode kann nicht aufgelöst werden. Sorry, ich weiß nicht wirklich, wie man dieses Ding mit simpleadapter umgehen kann. –

+0

Verwenden Sie diesen Link wird es sicherlich Ihr Problem zu lösen. Http://www.learn2crack.com/2013/10/android-asynctask-json-parsing-example.html – Drv

+0

es lehrt nicht Array oder Listview, das ist nicht Schleifen-Methode was ich habe kein Problem –