从列表中的服务器读取/详细信息Android中的片段

时间:2014-06-23 09:39:45

标签: android android-fragments

我正在使用此代码/概念:

Android Fragments

我想要实现的是,在选择的项目上(如下所示),我想将项目发送到服务器,让它在那一侧处理(我可以做)并检索String发回并使用该字符串更新列表/详细信息片段的详细信息部分。是否有人通过一些代码帮助我实现这一目标?

到目前为止我的代码如下:

public class MainActivity extends FragmentActivity implements HeadlinesFragment.OnHeadlineSelectedListener 
 {

XMLCreator x = new XMLCreator();
/** Called when the activity is first created. */

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.news_articles);

    // Check whether the activity is using the layout version with
    // the fragment_container FrameLayout. If so, we must add the first fragment
    if (findViewById(R.id.fragment_container) != null) 
    {

        // However, if we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        if (savedInstanceState != null) 
        {
            return;
        }

        // Create an instance of ExampleFragment
        HeadlinesFragment firstFragment = new HeadlinesFragment();

        // In case this activity was started with special instructions from an Intent,
        // pass the Intent's extras to the fragment as arguments
        firstFragment.setArguments(getIntent().getExtras());

        // Add the fragment to the 'fragment_container' FrameLayout
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, firstFragment).commit();

    }

    postToServer();
}

public void postToServer()
{
    new Connection().execute();
}

public void onArticleSelected(int position) 
{
    // The user selected the headline of an article from the HeadlinesFragment

    // Capture the article fragment from the activity layout
    ArticleFragment articleFrag = (ArticleFragment)getSupportFragmentManager().findFragmentById(R.id.article_fragment);

    if (articleFrag != null) 
    {
        // If article frag is available, we're in two-pane layout...

        // Call a method in the ArticleFragment to update its content
        String Day = "";
        Day = Ipsum.Headlines[position];
        Document doc;
            try 
            {
                doc = x.createDoc();
                Element tutor = doc.createElement("Query");
                tutor.appendChild(x.createDay(doc, Day, "GetSessionByDay"));
                doc.appendChild(tutor);
                String s = x.getStringFromDocument(doc);
                //connection.sendData(s);

                                  //Want to send and receive strings here
            } 
            catch (Exception e) 
            {
                e.printStackTrace();
            }

            articleFrag.updateArticleView(position);
        }
    else 
    {
        // If the frag is not available, we're in the one-pane layout and must swap frags...

        // Create fragment and give it an argument for the selected article
        ArticleFragment newFragment = new ArticleFragment();
        Bundle args = new Bundle();
        args.putInt(ArticleFragment.ARG_POSITION, position);
        newFragment.setArguments(args);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);

        // Commit the transaction
        transaction.commit();
    }
}

public class Connection extends AsyncTask<Void, Void, String> 
{
    // the I/O streams that will be receiving/sending data from/to the
            // server
            private ObjectOutputStream output;
            private ObjectInputStream input;
            private String message = "";
            private Socket client;
    @Override
    protected void onPreExecute() 
    {
        // IMPORTANT: this method is synched with UI thread, so can access UI
        super.onPreExecute();
    }

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

        try 
        {
            client = new Socket("10.111.1.1", 5001);

        } catch (UnknownHostException e1) {

            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            output = new ObjectOutputStream(client.getOutputStream());
            output.flush();
            input = new ObjectInputStream(client.getInputStream());

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        do 
        {
            try 
            {
                message = (String) input.readObject();

            } 
            catch (ClassNotFoundException classNotFoundException) 
            {

            } catch (OptionalDataException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        while (!message.equals("SERVER>>> TERMINATE")); 

        try 
        {
            output.writeObject(message);
            output.flush();

        } catch (IOException ioException) 
        {

        }

        // sleep a bit, so this task isn't over before it starts
            try 
            {
                Thread.sleep(500);
            } catch (InterruptedException e) 
            {
                Log.e("TASK", "Error sleeping in CalculateTask");
            }

        // return value to be passed to onPostExecute of task initiator
        return message;
    }



    @Override
    protected void onProgressUpdate(Void... progress) 
    {
        // IMPORTANT: this method is synched with UI thread, so can access UI

    }

    @Override
    protected void onPostExecute(String result) 
    {
        // IMPORTANT: this method is synched with UI thread, so can access UI
        super.onPostExecute(result);
        // update UI
    }
}

}

2 个答案:

答案 0 :(得分:0)

postToServer()中创建方法MainActivity以执行AsyncTask。在片段

中的OnItemClickListner内调用此方法
((MainActivity)getActivity).postToServer();

Fragment中,创建一个处理UI更新的方法updateUI(String response),并在Activity完成后从您的父AsyncTask调用此方法。在OnPostExecute();

AsyncTask中调用此方法

答案 1 :(得分:0)

只需在方法getData()中调用Fragment中的服务器,我认为你必须实现AsynkTask。当您在DoInBackground()中收到该请求的回复时,只需将其传递给onPostExecute()并使用该响应并根据需要更新您的UI。