postTweet方法返回null

时间:2016-04-02 10:15:05

标签: java android json

这是我的代码:

 PostTweetDialog.java

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.codepath.apps.mysimpletweet.models.Tweet;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by AlecksJohanssen on 4/1/2016.
 */
public class PostTweetDialog extends DialogFragment  {

    private RestClient client;
    private PostTweetInterface dialogFragment;
    ArrayList<Tweet> tweets;
    TweetArrayAdapter adapter;
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.post_tweet, null);
        EditText etComposeTweet = (EditText) dialogView.findViewById(R.id.posttxt);
        final String body = String.valueOf(etComposeTweet.getText());
        tweets = new ArrayList<>();
        adapter = new TweetArrayAdapter(tweets);
        AlertDialog.Builder TweetDialog = new AlertDialog.Builder(getActivity());
        TweetDialog.setTitle("Post Tweet");
        TweetDialog.setView(dialogView)
                .setPositiveButton("Continue", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        client.postTweet(body, new JsonHttpResponseHandler() {

                            @Override
                            public void onSuccess(int statusCode, Header[] headers, JSONObject json) {
                                Tweet myNewTweet = Tweet.fromJSON(json);
                                Log.d("DEBUG",String.valueOf(json.toString()));
                                tweets.add(myNewTweet);
                                adapter.notifyDataSetChanged();

                            }
                            @Override
                            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                                Log.d("Error", errorResponse.toString());
                            }

                        });

                    }

                }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int id) {
                dialogFragment.onDialogNegativeClick(PostTweetDialog.this);
            }
        });
        return TweetDialog.create();

    }

这是我的PostTweet方法:

    public void postTweet(String body, AsyncHttpResponseHandler handler) {
    String apiUrl = getApiUrl("statuses/update.json");
    RequestParams params = new RequestParams();
    params.put("status", body);
    getClient().post(apiUrl, params, handler);
}

post_tweet.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/posttxt"
        android:inputType="text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginBottom="4dp"
        android:hint="Input your Tweet here" />
</LinearLayout>

TimelineActivity.java

public class TimelineActivity extends AppCompatActivity {
    private PostTweetDialog PostDialog = new PostTweetDialog();
    private RestClient client;
    private ArrayList<Tweet> Tweet;
    private TweetArrayAdapter taAdapter;
    private RecyclerView rvItems;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private int[] tabIcons = {
            R.drawable.ic_tab_favourite,
            R.drawable.ic_tab_call,

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timeline);
        rvItems = (RecyclerView) findViewById(R.id.rvItems);
        Tweet = new ArrayList<>();
        taAdapter = new TweetArrayAdapter(Tweet);
        rvItems.setAdapter(taAdapter);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        setupTabIcons();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        rvItems.setLayoutManager(new LinearLayoutManager(this));
        client = RestApplication.getRestClient();
        populateTimeline(1);
        rvItems.addOnScrollListener(new EndlessRecyclerViewScrollListener(linearLayoutManager) {
            @Override
            public void onLoadMore(int page, int totalItemsCount) {
                populateTimeline(page);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;

    }

    public void doThis(MenuItem item)
    {
        PostDialog.show(getFragmentManager(), "fragment_dialog");
    }

    private void populateTimeline(int page) {
        client.getHomeTimeline(new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                Tweet.addAll(com.codepath.apps.mysimpletweet.models.Tweet.fromJSONArray(response));
                int curSize = taAdapter.getItemCount();
                taAdapter.notifyItemRangeInserted(curSize, Tweet.size() - 1);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
            }
        }, page);
    }

    private void setupTabIcons() {
        tabLayout.getTabAt(0).setIcon(tabIcons[0]);
        tabLayout.getTabAt(1).setIcon(tabIcons[1]);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new OneFragment(), "ONE");
        adapter.addFrag(new TwoFragment(), "TWO");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }


}

} 我不知道为什么我不能使用我的postTweet方法,它总是返回null值。 这是错误NullValue

的gif

提前致谢:D。 P / S:它在此行client.postTweet(body, new JsonHttpResponseHandler() {

上表示空

1 个答案:

答案 0 :(得分:0)

如评论中所述,您没有在对话框类中初始化客户端。您可以更改活动代码以将客户端作为参数传递:

public class TimelineActivity extends AppCompatActivity {
    private PostTweetDialog PostDialog;
    private RestClient client;
    private ArrayList<Tweet> Tweet;
    private TweetArrayAdapter taAdapter;
    private RecyclerView rvItems;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private int[] tabIcons = {
            R.drawable.ic_tab_favourite,
            R.drawable.ic_tab_call,

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timeline);
        rvItems = (RecyclerView) findViewById(R.id.rvItems);
        Tweet = new ArrayList<>();
        taAdapter = new TweetArrayAdapter(Tweet);
        rvItems.setAdapter(taAdapter);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        setupTabIcons();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        rvItems.setLayoutManager(new LinearLayoutManager(this));
        client = RestApplication.getRestClient();
        PostDialog = new PostTweetDialog(client);

        ...
     }
     ...
 }

并在对话框类中添加一个相应的构造函数:

public class PostTweetDialog extends DialogFragment  {
    private RestClient client;
    private PostTweetInterface dialogFragment;
    ArrayList<Tweet> tweets;
    TweetArrayAdapter adapter;

    public PostTweetDialog(RestClient client) {
        this.client = client;
    }

    ...
}

<强>更新

为了解答您的问题,为什么clientnull

让我们看一下PostTweetDialog的代码......

在该类的第一行中,您声明私有变量client

    private RestClient client;

然后在onCreate中设置使用onClick的{​​{1}}回调。

client

但是,在课程 TweetDialog.setView(dialogView) .setPositiveButton("Continue", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { client.postTweet(body, new JsonHttpResponseHandler() { ... }); 中没有任何地方可以找到该可变的作业。因此,PostTweetDialog PostTweetDialog内的client始终未定义。

由于您可能希望使用活动使用的相同null,因此您有多种选择。

  1. 您可以通过构造函数(在我的原始答案中展示)或通过 setter RestClient引用传递给对话框类。
  2. 您可以将活动设置为client,并在已有OnClickListener的活动中实施onClick。但是,您需要将活动的引用传递给对话框类。