Android从数据库中的内容填充ListView

时间:2012-03-09 20:30:30

标签: android

我有这个Android活动代码:

package com.problemio;

import java.io.InputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

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

import com.problemio.LoginActivity.DownloadWebPageTask;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MyProblemsActivity extends ListActivity 
{
    static final String[] COUNTRIES = new String[] {};

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.problem);

        setListAdapter(new ArrayAdapter<String>(this, R.layout.my_problems, COUNTRIES));

        ListView lv = getListView();
        lv.setTextFilterEnabled(true);

        lv.setOnItemClickListener(new OnItemClickListener() 
        {
            public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) 
            {
              // When clicked, show a toast with the TextView text
              Toast.makeText(getApplicationContext(), (( TextView ) view).getText(),
                  Toast.LENGTH_SHORT).show();

              // For now just do something simple like display a responsive message
              Log.d( "MyProblemsActivity" , "A choice was made from the list");
            }
          });        

        // Check if person is logged in
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( MyProblemsActivity.this);
        final String user_id = prefs.getString( "user_id" , null ); 

        // If the user is not logged in, send them to log in
        if ( user_id == null )
        {
            Intent loginIntent = new Intent( MyProblemsActivity.this, LoginActivity.class);
            MyProblemsActivity.this.startActivity(loginIntent);         
        }        

        // Go to the database and display a list of problems, all clickable.
        sendFeedback( user_id );   
    }   

    public void sendFeedback(String user_id) 
    {  
        Log.d( "user_id in MyProblemsActivity" , user_id );

        String[] params = new String[] { "http://www.problemio.com/problems/get_users_problems_mobile.php", user_id };

        DownloadWebPageTask task = new DownloadWebPageTask();
        task.execute(params);        
    }              


    public void onItemClick(AdapterView<?> items, View v, int x, long y)
    {
        Log.d( "onItemClick: " , "In the onItemClick method of MyProblemsActivity" );

    }

    public class DownloadWebPageTask extends AsyncTask<String, Void, String> 
    {
        @Override
        protected String doInBackground(String... theParams) 
        {
            Log.d( "MyProblemsActivity" , "in doInBackground method." );

            String myUrl = theParams[0];
            final String user_id = theParams[1];

            Log.d( "Inner myURL: " , myUrl );
            Log.d( "user_id: " , user_id );

            String charset = "UTF-8";           
            String response = null;

            try 
            {               
                String query = String.format("user_id=%s", 
                         URLEncoder.encode(user_id, charset));

                final URL url = new URL( myUrl + "?" + query );

                final HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                conn.setDoOutput(true); 
                conn.setRequestMethod("POST");

                conn.setDoOutput(true);
                conn.setUseCaches(false);

                conn.connect();

                final InputStream is = conn.getInputStream();
                final byte[] buffer = new byte[8196];
                int readCount;
                final StringBuilder builder = new StringBuilder();
                while ((readCount = is.read(buffer)) > -1) 
                {
                    builder.append(new String(buffer, 0, readCount));
                }

                response = builder.toString();      
                Log.d( "After call, response: " , " " + response);
            } 
            catch (Exception e) 
            {
                    Log.d( "Exception: " , "Yup");
                    e.printStackTrace();
            }

            return response;
        }

        @Override
        protected void onPostExecute(String result) 
        {
            Log.d( "Post execute: " , "In the post-execute method: " + result );
            //textView.setText(result);

            if ( result != null && result == "no_such_user")
            {
                Log.d( "Post execute: " , "NOOOT  OKKKK" ); 
                // Show the user a message that they did not enter the right login

                Toast.makeText(getApplicationContext(), "Your email and password do not match out records. Please try again or create and account.", Toast.LENGTH_LONG).show(); 

                //final TextView login_error = (TextView) findViewById(R.id.login_error);

                //textView.setText("My Text Hellosss - wrong login");            



            }
            else
            {
                Log.d( "Post execute: " , "OKKKK, result: " + result );       

                // Unwrap the stuff from the JSON string

                String problem_title = null;
                String problem_id = null;

                try
                {
                    JSONArray obj = new JSONArray(result);
                    JSONObject o = obj.getJSONObject(0);                    

                    Log.d( "Title: " , "" + o.getString("problem_title") );       
                    Log.d( "id: " , "" + o.getString("problem_id") );      

                    problem_title = o.getString("problem_title");
                    problem_id = o.getString("problem_id");
                }
                catch ( Exception e )
                {
                    Log.d( "JSON ERRORZ: " , "some crap happened " + e.getMessage() );
                }

                // Now not sure what to do :)

            }
        }        
    }
}

我希望查询远程数据库,获取项目列表并显示它们。但我不确定在从远程服务器上取回JSON之后如何使用该信息更新屏幕。

另外,我的观点xml文件是这样的:

<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>    

但我不太清楚如何显示从db动态获取的项目列表。

谢谢!

1 个答案:

答案 0 :(得分:1)

每次要将其他数据添加到列表视图时,请使用适配器的add方法,然后调用适配器的notifyDataSetChanged()方法,以便更新UI中的更改。