我添加一个新的listview后,如何在android中更新listview

时间:2021-08-17 07:18:02

I'm doing something like contact app using a json

我在用json做一些联系应用

I can view a contact and add a new one but I can't make the contact update automatically after I add a new one ( in my database already update ). I have to run my app again in eclipse to see a new contact

我可以查看一个联系人并添加一个新的联系人,但是我不能在添加一个新的联系人之后自动更新联系人(在我的数据库中已经更新了)。我必须在eclipse中再次运行我的应用程序才能看到一个新的联系人

some of my main code is like this

我的一些主要代码是这样的

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.*;
import android.content.*;
import android.database.Cursor;
import android.os.Bundle;
import android.view.*;
import android.widget.*;

public class MainActivity extends ListActivity {

    private Cursor friendsCursor = null;
    int position;
    private ArrayList<Data> friends = null;
    DateFormat fDateTimeDisplay = new SimpleDateFormat("dd-MM-yyyy");
    DateFormat fDateTime = new SimpleDateFormat("yyyy-MM-dd");
    public static  String friendURL = "http://-----/friend.php";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        friends = new ArrayList<Data>();
        setListAdapter(new DataAdapter()); 

        try
        {
            JSONArray jArray = new JSONArray(getServerData());
            String name, address, gender;
            long code;
            Date DOB;
            friends.clear();
            for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i);
                code = json_data.getLong("FriendCode");
                name = json_data.getString("FriendName");
                address = json_data.getString("FriendAddress");
                gender = json_data.getString("FriendGender");
                DOB = fDateTime.parse(json_data.getString("FriendDOB"));
                Data data = new Data(name, address, gender, DOB,code);
                friends.add(data);  } 

        }catch(JSONException e){
            //Display error message
            Toast.makeText(this, "Error parsing data " + e.toString(), Toast.LENGTH_LONG).show();
        }
        catch (ParseException pe) {
            Toast.makeText(this, "Error parsing data " + pe.toString(), Toast.LENGTH_LONG).show();
        }
        registerForContextMenu(getListView());
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        new MenuInflater(this).inflate(R.menu.option, menu);
        return(super.onCreateOptionsMenu(menu));
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add:
                Intent intent = new Intent(this, AddActivity.class);
                intent.putExtra("code", 1);
                startActivityForResult(intent, 1);

                return(true);

        }       


        return(super.onOptionsItemSelected(item));
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK)
        {       
        }
    }


    private String getServerData() {  
        InputStream is = null;

        String result = "";

        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(friendURL);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        }catch(Exception e){
            Toast.makeText(this, "Error in http connection " + e.toString(), Toast.LENGTH_LONG).show();
        }

        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();
            result=sb.toString();
        }catch(Exception e){
            Toast.makeText(this, "Error converting result " + e.toString(), Toast.LENGTH_LONG).show();
        }
        return result;
    }


    class DataAdapter extends ArrayAdapter<Data> {
        DataAdapter() {
            super(MainActivity.this, R.layout.row, friends);
        }

        public View getView(int position, View convertView, ViewGroup parent) {     
            View row = convertView;         
            if (row == null) {                                                  
                LayoutInflater inflater = getLayoutInflater();              
                row = inflater.inflate(R.layout.row, parent, false);
            }

            ViewHolder holder = (ViewHolder)row.getTag();           
            if (holder == null) {                                                   
                holder = new ViewHolder(row);
                row.setTag(holder);
            }
            holder.code.setText(Long.toString((friends.get(position).getcode())));  
            holder.txtName.setText(friends.get(position).getName());
            holder.txtAddress.setText(friends.get(position).getAddress());
            holder.txtGender.setText(friends.get(position).getGender());
            holder.txtDOB.setText(fDateTimeDisplay.format(friends.get(position).getDOB()));
            return(row);
        }
    }

}

and when i want to add a new contact I use Intent AddActivity to open a new layout call add

当我想添加一个新的联系人时,我使用Intent AddActivity来打开一个新的布局调用add

this is some code of my AddActivity

这是我的AddActivity的一些代码

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.*;
import java.util.*;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.*;
import android.os.Bundle;
import android.view.*;
import android.widget.*;

public class AddActivity extends Activity {
    public static  String friendInsertURL = "http://----/friendInsert.php";



    Calendar calendar = Calendar.getInstance();
    DateFormat fDateTime = new SimpleDateFormat("yyyy-MM-dd");
    DateFormat fDateTimeDisplay = new SimpleDateFormat("dd-MM-yyyy");
    long code;
    EditText editName, editAddress;
    RadioButton rbMale, rbFemale;
    TextView txtDOBEdit;
    String gender;
    int position;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add);

        editName = (EditText)findViewById(R.id.editName);
        editAddress = (EditText)findViewById(R.id.editAddress);
        txtDOBEdit = (TextView)findViewById(R.id.txtDOBEdit);
        rbMale = (RadioButton)findViewById(R.id.rbMale);
        rbFemale = (RadioButton)findViewById(R.id.rbFemale);
        editName.setText("");
        editAddress.setText("");
        calendar = Calendar.getInstance();      
        txtDOBEdit.setText(fDateTimeDisplay.format(calendar.getTime()));
        rbMale.setChecked(true);
    }


    private String setServerData(String mode, String name, String address, String gender, String dob) {        
        InputStream is = null;

        String save = "";

        ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();


        if (mode.equals("INSERT")) {   

            parameters.add(new BasicNameValuePair("FriendName", name));
            parameters.add(new BasicNameValuePair("FriendAddress", address));
            parameters.add(new BasicNameValuePair("FriendGender", gender));
            parameters.add(new BasicNameValuePair("FriendDOB", dob));
            friendInsertURL = "http://----/friendInsert.php";
        }

        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(friendInsertURL );
            httppost.setEntity(new UrlEncodedFormEntity(parameters));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        }catch(Exception e){
            Toast.makeText(this, "Error in http connection " + e.toString(), Toast.LENGTH_LONG).show();
        }

        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();
            save=sb.toString();
        }catch(Exception e){
            Toast.makeText(this, "Error converting result " + e.toString(), Toast.LENGTH_LONG).show();
        }
        return save;
    }

    public void chooseDate(View v) {        
        new DatePickerDialog(this, d,
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH))
                .show();        
    }
    DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, monthOfYear);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            TextView txtDOBEdit = (TextView)findViewById(R.id.txtDOBEdit);
            txtDOBEdit.setText(fDateTimeDisplay.format(calendar.getTime()));
        }
    };


    public void setSave(View view){

        String save;
        EditText editName = (EditText)findViewById(R.id.editName);
        EditText editAddress = (EditText)findViewById(R.id.editAddress);
        RadioButton rbMale = (RadioButton)findViewById(R.id.rbMale);

        if (rbMale.isChecked()){
            gender = "Male";}
        else{
            gender = "Female";          
        }

            save = setServerData("INSERT", editName.getText().toString(), editAddress.getText().toString(), gender, fDateTime.format(calendar.getTime()));

        finish();
    }
}

I already search and found that I have to use adapter.notifyDataSetChanged() to update my adapter but when I put this code in my AddActivity

我已经搜索并发现我必须使用adapter.notifyDataSetChanged()来更新我的适配器,但是当我将此代码放入AddActivity时

    ArrayAdapter<Data> adapter = (ArrayAdapter<Data>)getListAdapter();

the getListAdapter error in there and I can't put a ListActivity, it cause my app error when I run it.

这里的getListAdapter错误我不能放一个ListActivity,当我运行它时,它会导致应用程序错误。

my problem is how to make my adapter update so I can always see my contact update wherever I add a new one ?

我的问题是如何使我的适配器更新,这样我就可以随时看到我的联系人更新,我在哪里添加一个新的?

found something:

发现的东西:

my code for add is add into database not the adapter .. is it because of that ? is it true then how to add into adapter ? is it in MainActivity or AddActivity ?

我添加的代码是添加到数据库中,而不是适配器。是因为这个原因吗?那么如何添加到适配器是真的吗?是主活动还是附加活动?

N.B.: my listview is using viewholder to show the content..

注意:我的列表是用viewholder来显示内容。

really need help.. I already try all code that i know but still can't make it update except exit and run again the app

真的需要帮助. .我已经尝试了所有我知道的代码,但是仍然不能更新,除了退出并再次运行应用程序

1 个解决方案

#1


1  

Changes needed in your code and paste it in your project

代码中需要的更改并将其粘贴到项目中

public class MainActivity extends ListActivity {

private ArrayList<Data> friends;
private ArrayAdapter adapter;
private ListViewlistview;

@Override
public void onCreate(Bundle savedInstanceState) {

    friends = new ArrayList<Data>();
    listview = (ListView) findViewById(R.id.listview_id);
    adapter = new ArrayAdapter<Data>(this, R.id.list, friends);
    listview.setAdapter(adapter);
}

This will update the listview, so you can call it after adding new one to a 'friends' list.

这将更新listview,因此您可以在向“好友”列表中添加新列表之后调用它。

adapter.notifyDataSetChanged();

#1


1  

Changes needed in your code and paste it in your project

代码中需要的更改并将其粘贴到项目中

public class MainActivity extends ListActivity {

private ArrayList<Data> friends;
private ArrayAdapter adapter;
private ListViewlistview;

@Override
public void onCreate(Bundle savedInstanceState) {

    friends = new ArrayList<Data>();
    listview = (ListView) findViewById(R.id.listview_id);
    adapter = new ArrayAdapter<Data>(this, R.id.list, friends);
    listview.setAdapter(adapter);
}

This will update the listview, so you can call it after adding new one to a 'friends' list.

这将更新listview,因此您可以在向“好友”列表中添加新列表之后调用它。

adapter.notifyDataSetChanged();