简体   繁体   中英

ANDROID: Get next item from listview to editText after 1st item is saved

What I have: (1st Functionality) I have a listview activity populated with items from JSON url. I have another activity where I get the listItem to editText field and then click "save", which saves the value to dB.

What I additionally want: (2nd Functionality) When I click save, rather than going back to listview and select next listItem, I want the editText to fill the new listItem for me. But I am making errors in every step.

Below is the code that I have for 1st Functionality. I know it is just few lines to achieve the 2nd functionality but struggling with that.

The problem here is I cannot call the list String variable from one activity to another and assign position or a counter to it. Suggest me what to change here.

MainActivity.java (Class containing ListView populated with item from json url)

package com.example.app.listview;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

    ListView listView;
    ArrayList<String> tutorialList = new ArrayList<String>();

    private final static String URL = "-----json------url----file";

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

        new FetchDataTask().execute(URL);

    }

    private class FetchDataTask extends AsyncTask<String, Void, String>{

        @Override
        protected String doInBackground(String... params) {

            InputStream inputStream = null;
            String result= null;
            HttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(params[0]);

            try {

                HttpResponse response = client.execute(httpGet);
                inputStream = response.getEntity().getContent();

                // convert inputstream to string
                if(inputStream != null){
                    result = convertInputStreamToString(inputStream);
                    Log.i("App", "Data received:" +result);

                }
                else
                    result = "Failed to fetch data";

                return result;

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String dataFetched) {
            //parse the JSON data and then display
            parseJSON(dataFetched);
        }


        private String convertInputStreamToString(InputStream inputStream) throws IOException{
            BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
            String line = "";
            String result = "";
            while((line = bufferedReader.readLine()) != null)
                result += line;

            inputStream.close();
            return result;

        }

        private void parseJSON(String data){

            try{
                JSONArray jsonMainNode = new JSONArray(data);

                int jsonArrLength = jsonMainNode.length();

                for(int i=0; i < jsonArrLength; i++) {
                    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                    String postTitle = jsonChildNode.getString("codeid");
                    tutorialList.add(postTitle);
                }

                // Get ListView object from xml
                listView = (ListView) findViewById(R.id.list);

                // Define a new Adapter
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, tutorialList);

//                 Assign adapter to ListView
                listView.setAdapter(adapter);
                        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                                Intent intent =  new Intent(MainActivity.this, AddFlowerInfo.class);
                                intent.putExtra("Code", listView.getItemAtPosition(i).toString());
                                startActivity(intent);
                            }
        });

            }catch(Exception e){
                Log.i("App", "Error parsing data" +e.getMessage());

            }
        }
    }
}

editText.java (class containing editText field and save to dB)

package com.example.app.listview;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.util.Log;
import android.view.View;

public class AddFlowerInfo extends AppCompatActivity  {
    EditText editText; //non editable codeid <<----<<----<<----<<--<<---<<1
    private static final String TAG = "AddFlowerInfo";

    Button savedata;
    String noneditcode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_flower_info);
        editText = (EditText) findViewById(R.id.codeid);
        savedata = (Button) findViewById(R.id.saveflowerinfo);

        final String Codeholder = getIntent().getStringExtra("Code");
        editText.setText(Codeholder);
      }

    public void dataflowerinfo(View view){

        noneditcode = editText.getText().toString();


        String method = "FlowerInfo";
        BackgroundTask2 backgroundTask2 = new BackgroundTask2(this);
        backgroundTask2.execute(method, noneditcode);
        finish();

    }

UPDATE AddFlowerInfo.java (OnCreate) and (OnClick)

public class AddFlowerInfo extends AppCompatActivity  {
    EditText editText; //non editable codeid <<----<<----<<----<<--<<---<<1
    private static final String TAG = "AddFlowerInfo";

    Button savedata;
    int i=0;

    String noneditcode;
    int pos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_flower_info);
        editText = (EditText) findViewById(R.id.codeid);
        savedata = (Button) findViewById(R.id.saveflowerinfo);

        Intent i =getIntent();
        final ArrayList<String> list = i.getStringArrayListExtra("key");
          pos = i.getIntExtra("position", 0);

//        final String Codeholder = getIntent().getStringExtra("Code");
        editText.setText(list.get(pos));

        savedata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =  new Intent(AddFlowerInfo.this, AddFlowerInfo.class);
                startActivity(intent);

                ++pos;
                if(pos<=list.size()-1)

                    list.get(pos);

            }
        });

Pass your data from activity like this

 ArrayList<String> tutorialList = new ArrayList<String>();  
 Intent intent = new Intent(ActivityName.this, Second.class);
 intent.putStringArrayListExtra("key", tutorialList);
 startActivity(intent);

To retrive at AddFlowerInfo

Intent i = getIntent();  
ArrayList<String> list = i.getStringArrayListExtra("key");

Then as you are retrieving data from list using position ,each time after saving call data at next position

You need to send complete array to AddFlowerInfo with the position, so change your onItemClick code:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                Intent intent =  new Intent(MainActivity.this, AddFlowerInfo.class);
                intent.putExtra("position", i);
                intent.putStringArrayListExtra("array",tutorialList);
                startActivity(intent);
            }
        });

Now in AddFlowerInfo :

 Intent i = getIntent();
        ArrayList<String> tutorialList = i.getStringArrayListExtra("array");
        int pos=i.getIntExtra("position",0);

Use this position to get item from tutorialList .

To update data when user gets back to previous activity, place this code:

 new FetchDataTask().execute(URL);

into onResume method.

Update

After saving first item to edit second item use:

++pos;
if(pos<=tutorialList.size()-1)
    editText.setText(tutorialList.get(pos)); 
else
 {
   // you are after last item do whatever you want
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM