简体   繁体   English

ANDROID:保存第一个项目后,将列表视图中的下一个项目获取到editText

[英]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. 我所拥有的:(第一功能)我有一个listview活动,其中填充了JSON url中的项目。 I have another activity where I get the listItem to editText field and then click "save", which saves the value to dB. 我还有另一个活动,将listItem移到editText字段,然后单击“保存”,将值保存为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. 我还想要什么:(第二个功能)当我单击保存时,而不是返回到列表视图并选择下一个listItem,我希望editText为我填充新的listItem。 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. 这里的问题是我无法从一个活动到另一个活动调用列表String变量,也无法为其分配位置或计数器。 Suggest me what to change here. 建议我在这里更改什么。

MainActivity.java (Class containing ListView populated with item from json url) MainActivity.java (包含ListView的类,其中填充了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) editText.java (包含editText字段并保存为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) UPDATE AddFlowerInfo.java(OnCreate)和(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 检索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: 你需要完整的阵列发送到AddFlowerInfo与位置,所以改变你onItemClick代码:

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 : 现在在AddFlowerInfo

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

Use this position to get item from tutorialList . 使用此位置从tutorialList获取项目。

To update data when user gets back to previous activity, place this code: 要在用户返回上一个活动时更新数据,请放置以下代码:

 new FetchDataTask().execute(URL);

into onResume method. 进入onResume方法。

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
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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