I'm developing wordpress android app which loads Wordpress post data in android webview. I'm using retrofit & JSON API to fetch data from my Wordpress site. My app worked fine in android API LEVEL 26 but the problem is I need API 28+ to upload to google play store. I migrated to androidx API LEVEL 29. post were not getting loaded showing ERR_CLEARTEXT_NOT_PERMITTED so I used "android:usesCleartextTraffic=true" post was loading but the problem is HTML entities like –,“,’ etc failed to decode and decoded as & and remaining lines of the post are not loaded after this. I dint use "android:usesCleartextTraffic=true" in API LEVEL 26 but it works fine without any error. I'm searching a solution for my problem I didn't find satisfying answers anywhere. I'm stuck at this point. So I'm trying alternative method for "android:usesCleartextTraffic=true". I have "text to speech" function in my app its working absolutely fine I mean its reading entire post which is not visible in android webview. Kindly suggest. Please find the code for your reference.
WEBVIEW SCREESHOT
this is my postdetails activity
Postdetails.java
package ak.wp.meto.activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.fragment.app.FragmentManager;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import ak.wp.meto.R;
import ak.wp.meto.adapters.CommentsAdapter;
import ak.wp.meto.api.http.ApiUtils;
import ak.wp.meto.api.models.posts.post.CommentsAndReplies;
import ak.wp.meto.api.models.posts.post.PostDetails;
import ak.wp.meto.api.params.HttpParams;
import ak.wp.meto.data.constant.AppConstant;
import ak.wp.meto.data.sqlite.FavouriteDbController;
import ak.wp.meto.fragment.WriteACommentFragment;
import ak.wp.meto.listeners.ListItemClickListener;
import ak.wp.meto.models.FavouriteModel;
import ak.wp.meto.utility.ActivityUtils;
import ak.wp.meto.utility.AppUtils;
import ak.wp.meto.utility.TtsEngine;
import ak.wp.meto.webengine.WebEngine;
import ak.wp.meto.webengine.WebListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class PostDetailsActivity extends BaseActivity implements WriteACommentFragment.OnCompleteListener {
// Variables
private Activity mActivity;
private Context mContext;
// init views
private RelativeLayout lytPostDetailsView, lytCommentDetails;
private int clickedPostId;
private ImageView imgPost;
private TextView tvPostTitle, tvPostAuthor, tvPostDate, tvCommnentList;
private WebView webView;
private FloatingActionButton fabWriteAComment;
private ImageButton imgBtnSpeaker, imgBtnFav, imgBtnShare;
private PostDetails model = null;
// Favourites view
private List<FavouriteModel> favouriteList;
private FavouriteDbController favouriteDbController;
private boolean isFavourite = false;
// Comments view
private List<CommentsAndReplies> commentList;
private List<CommentsAndReplies> zeroParentComments;
List<CommentsAndReplies> onlyThreeComments;
private int mPerPage = 5;
private RecyclerView rvComments;
private CommentsAdapter commentsAdapter = null;
// Text to speech
private TtsEngine ttsEngine;
private boolean isTtsPlaying = false;
private String ttsText;
private WebEngine webEngine;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initVar();
initView();
initFunctionality();
initListener();
}
private void initVar() {
mActivity = PostDetailsActivity.this;
mContext = mActivity.getApplicationContext();
// Favourites view
favouriteList = new ArrayList<>();
// Comments view
commentList = new ArrayList<>();
zeroParentComments = new ArrayList<>();
onlyThreeComments = new ArrayList<>();
Intent intent = getIntent();
if (intent != null) {
clickedPostId = getIntent().getIntExtra(AppConstant.BUNDLE_KEY_POST_ID, 0);
}
}
private void initView() {
setContentView(R.layout.activity_post_details);
lytPostDetailsView = (RelativeLayout) findViewById(R.id.lyt_post_details);
lytCommentDetails = (RelativeLayout) findViewById(R.id.lyt_comment_list);
//lytParentView.setVisibility(View.GONE);
imgPost = (ImageView) findViewById(R.id.post_img);
tvPostTitle = (TextView) findViewById(R.id.title_text);
tvPostAuthor = (TextView) findViewById(R.id.post_author);
tvPostDate = (TextView) findViewById(R.id.date_text);
imgBtnSpeaker = (ImageButton) findViewById(R.id.imgBtnSpeaker);
imgBtnFav = (ImageButton) findViewById(R.id.imgBtnFavourite);
imgBtnShare = (ImageButton) findViewById(R.id.imgBtnShare);
initWebEngine();
tvCommnentList = (TextView) findViewById(R.id.comment_count);
fabWriteAComment = (FloatingActionButton) findViewById(R.id.fab_new_comment);
rvComments = (RecyclerView) findViewById(R.id.rvComments);
rvComments.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
initLoader();
initToolbar();
enableBackButton();
}
public void initWebEngine() {
webView = (WebView) findViewById(R.id.web_view);
webEngine = new WebEngine(webView, mActivity);
webEngine.initWebView();
webEngine.initListeners(new WebListener() {
#Override
public void onStart() {
initLoader();
}
#Override
public void onLoaded() {
hideLoader();
}
#Override
public void onProgress(int progress) {
}
#Override
public void onNetworkError() {
showEmptyView();
}
#Override
public void onPageTitle(String title) {
}
});
}
private void initFunctionality() {
favouriteDbController = new FavouriteDbController(mContext);
favouriteList.addAll(favouriteDbController.getAllData());
for (int i = 0; i < favouriteList.size(); i++) {
if (favouriteList.get(i).getPostId() == clickedPostId) {
isFavourite = true;
break;
}
}
ttsEngine = new TtsEngine(mActivity);
commentsAdapter = new CommentsAdapter(mActivity, (ArrayList) commentList, (ArrayList) onlyThreeComments);
rvComments.setAdapter(commentsAdapter);
showLoader();
loadPostDetails();
// show full-screen ads
// AdUtils.getInstance(mContext).showFullScreenAd();
}
public void setFavImage() {
if (isFavourite) {
imgBtnFav.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_book));
} else {
imgBtnFav.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_un_book));
}
}
public void initListener() {
imgBtnSpeaker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (model != null) {
toggleTtsPlay();
}
}
});
imgBtnFav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (model != null) {
isFavourite = !isFavourite;
if (isFavourite) {
String imgUrl = null;
if (model.getEmbedded().getWpFeaturedMedias().size() >= 1) {
imgUrl = model.getEmbedded().getWpFeaturedMedias().get(0).getMediaDetails().getSizes().getFullSize().getSourceUrl();
}
favouriteDbController.insertData(
model.getID().intValue(),
imgUrl,
model.getTitle().getRendered(),
model.getOldDate(),
model.getEmbedded().getWpTerms().get(0).get(0).getName()
);
} else {
favouriteDbController.deleteFav(clickedPostId);
}
setFavImage();
}
}
});
imgBtnShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (model != null) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, model.getPageUrl());
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
}
});
commentsAdapter.setItemClickListener(new ListItemClickListener() {
#Override
public void onItemClick(int position, View view) {
int id = view.getId();
CommentsAndReplies clickedComment = zeroParentComments.get(position);
switch (id) {
case R.id.list_item:
ActivityUtils.getInstance().invokeCommentDetails(mActivity, CommentDetailsActivity.class, (ArrayList) commentList, clickedPostId, clickedComment, false, false);
break;
case R.id.reply_text:
ActivityUtils.getInstance().invokeCommentDetails(mActivity, CommentDetailsActivity.class, (ArrayList) commentList, clickedPostId, clickedComment, true, false);
break;
default:
break;
}
}
});
tvCommnentList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityUtils.getInstance().invokeCommentList(mActivity,
CommentListActivity.class,
(ArrayList) commentList,
(ArrayList) zeroParentComments,
clickedPostId,
false);
}
});
fabWriteAComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getSupportFragmentManager();
WriteACommentFragment dialog = WriteACommentFragment.newInstance(clickedPostId, AppConstant.THIS_IS_COMMENT);
dialog.show(manager, AppConstant.BUNDLE_KEY_DIALOG_FRAGMENT);
}
});
}
public void loadPostDetails() {
ApiUtils.getApiInterface().getPostDetails(clickedPostId).enqueue(new Callback<PostDetails>() {
#Override
public void onResponse(Call<PostDetails> call, Response<PostDetails> response) {
if (response.isSuccessful()) {
// bind data
model = response.body();
PostDetails m = model;
// visible parent view
lytPostDetailsView.setVisibility(View.VISIBLE);
// visible comments button
fabWriteAComment.setVisibility(View.VISIBLE);
loadCommentsAndReplies(model.getLinks().getRepliesList().get(0).getHref());
setFavImage();
tvPostTitle.setText(Html.fromHtml(model.getTitle().getRendered()));
String imgUrl = null;
if (model.getEmbedded().getWpFeaturedMedias().size() > 0) {
if (model.getEmbedded().getWpFeaturedMedias().get(0).getMediaDetails() != null) {
if (model.getEmbedded().getWpFeaturedMedias().get(0).getMediaDetails().getSizes().getFullSize().getSourceUrl() != null) {
imgUrl = model.getEmbedded().getWpFeaturedMedias().get(0).getMediaDetails().getSizes().getFullSize().getSourceUrl();
}
}
}
if (imgUrl != null) {
Glide.with(getApplicationContext())
.load(imgUrl)
.into(imgPost);
}
String author = null;
if (model.getEmbedded().getAuthors().size() >= 1) {
author = model.getEmbedded().getAuthors().get(0).getName();
}
if (author == null) {
author = getString(R.string.admin);
}
tvPostAuthor.setText(Html.fromHtml(author));
String oldDate = model.getOldDate();
String newDate = AppUtils.getFormattedDate(oldDate);
if (newDate != null) {
tvPostDate.setText(Html.fromHtml(newDate));
}
String contentText = model.getContent().getRendered();
ttsText = new StringBuilder(Html.fromHtml(model.getTitle().getRendered())).append(AppConstant.DOT).append(Html.fromHtml(model.getContent().getRendered())).toString();
webView.loadData(contentText, "text/html", "UTF-8"); //comment
contentText = new StringBuilder().append(AppConstant.CSS_PROPERTIES).append(contentText).toString();
webEngine.loadHtml(contentText);
} else {
showEmptyView();
}
}
#Override
public void onFailure(Call<PostDetails> call, Throwable t) {
t.printStackTrace();
// hide common loader
hideLoader();
// show empty view
showEmptyView();
}
});
}
public void loadCommentsAndReplies(final String commentsAndRepliesLink) {
ApiUtils.getApiInterface().getCommentsAndReplies(commentsAndRepliesLink, mPerPage).enqueue(new Callback<List<CommentsAndReplies>>() {
#Override
public void onResponse(Call<List<CommentsAndReplies>> call, Response<List<CommentsAndReplies>> response) {
if (response.isSuccessful()) {
int totalItems = Integer.parseInt(response.headers().get(HttpParams.HEADER_TOTAL_ITEM));
int totalPages = Integer.parseInt(response.headers().get(HttpParams.HEADER_TOTAL_PAGE));
if (totalPages > 1) {
mPerPage = mPerPage * totalPages;
loadCommentsAndReplies(commentsAndRepliesLink);
} else {
if (!commentList.isEmpty() || !zeroParentComments.isEmpty() || !onlyThreeComments.isEmpty()) {
commentList.clear();
zeroParentComments.clear();
onlyThreeComments.clear();
}
commentList.addAll(response.body());
lytCommentDetails.setVisibility(View.VISIBLE);
if (commentList.size() > 0) {
for (CommentsAndReplies commentsAndReplies : commentList) {
if (commentsAndReplies.getParent().intValue() == 0) {
zeroParentComments.add(commentsAndReplies);
}
}
if (zeroParentComments.size() >= 3) {
for (int i = 0; i < 3; i++) {
onlyThreeComments.add(zeroParentComments.get(i));
}
} else {
for (CommentsAndReplies commentsAndReplies : zeroParentComments) {
onlyThreeComments.add(commentsAndReplies);
}
}
commentsAdapter.notifyDataSetChanged();
tvCommnentList.setText(String.format(getString(R.string.all_comment), commentList.size()));
tvCommnentList.setClickable(true);
} else {
tvCommnentList.setClickable(false);
}
}
}
}
#Override
public void onFailure(Call<List<CommentsAndReplies>> call, Throwable t) {
showEmptyView();
t.printStackTrace();
}
});
}
private void toggleTtsPlay() {
if (isTtsPlaying) {
ttsEngine.releaseEngine();
isTtsPlaying = false;
} else {
ttsEngine.startEngine(ttsText);
isTtsPlaying = true;
}
toggleTtsView();
}
private void toggleTtsView() {
if (isTtsPlaying) {
imgBtnSpeaker.setImageDrawable(getResources().getDrawable(R.drawable.ic_speaker_stop));
} else {
imgBtnSpeaker.setImageDrawable(getResources().getDrawable(R.drawable.ic_speaker));
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
finish();
}
#Override
protected void onStop() {
super.onStop();
ttsEngine.releaseEngine();
}
#Override
protected void onDestroy() {
super.onDestroy();
ttsEngine.releaseEngine();
model = null;
}
#Override
protected void onResume() {
super.onResume();
if (isTtsPlaying) {
isTtsPlaying = false;
imgBtnSpeaker.setImageDrawable(getResources().getDrawable(R.drawable.ic_speaker));
}
}
#Override
public void onComplete(Boolean isCommentSuccessful, CommentsAndReplies commentsAndReplies) {
if (isCommentSuccessful) {
loadCommentsAndReplies(model.getLinks().getRepliesList().get(0).getHref());
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == AppConstant.REQUEST_CODE_COMMENT) {
if (data == null) {
return;
}
boolean isCommentSuccessful = CommentListActivity.wasCommentSuccessful(data);
if (isCommentSuccessful) {
loadCommentsAndReplies(model.getLinks().getRepliesList().get(0).getHref());
}
}
}
}
activity_post_details.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:fitsSystemWindows="true">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="#+id/post_img"
android:layout_width="match_parent"
android:layout_height="#dimen/margin_250dp"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
android:src="#color/white"
app:layout_collapseMode="parallax" />
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/imgBtnSpeaker"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:layout_toLeftOf="#id/imgBtnFavourite"
android:padding="5dp"
android:scaleType="centerInside"
android:src="#drawable/ic_speaker" />
</RelativeLayout>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/content_post_details" />
<include layout="#layout/content_comments" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab_new_comment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/activity_vertical_margin"
android:src="#drawable/ic_fab"
android:visibility="gone" />
<include layout="#layout/view_common_loader" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>
content_post_details.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/lyt_post_details"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:visibility="gone">
<LinearLayout
android:id="#+id/li_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/margin_8dp"
android:layout_marginTop="#dimen/margin_8dp"
android:orientation="horizontal"
android:weightSum="1">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/margin_20dp"
android:layout_weight="0.5"
android:gravity="center_vertical"
android:padding="#dimen/margin_8dp">
<ImageView
android:id="#+id/author_image"
android:layout_width="#dimen/margin_30dp"
android:layout_height="#dimen/margin_30dp"
android:background="#drawable/ic_author" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/margin_20dp"
android:layout_weight="0.5"
android:gravity="center_vertical"
android:padding="#dimen/margin_8dp">
</LinearLayout>
</LinearLayout>
<View
android:id="#+id/viewDivider"
android:layout_width="match_parent"
android:layout_height="0.7dp"
android:layout_below="#id/li_layout"
android:layout_marginLeft="#dimen/margin_15dp"
android:layout_marginRight="#dimen/margin_15dp"
android:background="#color/toolbar_boarder" />
<TextView
android:id="#+id/title_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/viewDivider"
android:layout_margin="#dimen/margin_8dp"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold"
tools:text="This is sample text do yoy know that it supports multi-line" />
<WebView
android:id="#+id/web_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title_text"
android:layout_margin="#dimen/margin_8dp"
android:paddingBottom="#dimen/margin_8dp" />
</RelativeLayout>
Related
I've been trying to fix my code for a long time. I looked so so many places to find a solution but no avail. If you look at my code and show me why my TextViews in RecylerView is not showed, that'd be great.
I am trying to use WebSocket-ing and fetch data from internet. That should be displayed in the RecyclerView in a constantly updated way. Data ledgers from ripple servers are coming with a natural delay. I want to show their some aspects in RecyclerView. All TextViews can change in content, they are just to try it out.
Here is my WebSocketActivity code:
package com.example.menes.searchcode.Websocketing;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.example.menes.searchcode.R;
import com.google.gson.Gson;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONObject;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class WebSocketActivity extends AppCompatActivity implements MyWebSocketAdapter.OnItemClickListener {
private RecyclerView webSocketRecyclerView;// = findViewById(R.id.myRecyclerView);
private MyWebSocketAdapter myWebSocketAdapter;
List<LedgerResult> adapterLedgerResultList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.websocket_and_button_thing);
Button startWebsocketButton = findViewById(R.id.startButton);
final Button stopWebSocketButton = findViewById(R.id.stopButton);
startWebsocketButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if(adapterLedgerResultList.size() == 0)
Toast.makeText(WebSocketActivity.this,"Yes it is empty!, nice.",Toast.LENGTH_SHORT).show();
myWebSocketAdapter = new MyWebSocketAdapter(WebSocketActivity.this, adapterLedgerResultList);
webSocketRecyclerView = findViewById(R.id.myRecyclerView);
webSocketRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
webSocketRecyclerView.setAdapter(myWebSocketAdapter);
final MySimpleClient c = new MySimpleClient( new URI( "wss://s2.ripple.com:443" ));
c.connect();
stopWebSocketButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
c.close();
}
});
} catch (URISyntaxException e){
e.printStackTrace();
Toast.makeText(WebSocketActivity.this,"URISyntaxException occurred. Try again!",Toast.LENGTH_SHORT).show();
}
}
});
}
public void bindIt () {
//webSocketRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
myWebSocketAdapter.setOnItemClickListener(this);
webSocketRecyclerView.setHasFixedSize(true);
//webSocketRecyclerView.setAdapter(myWebSocketAdapter);
}
#Override
public void onItemClick(int position) {
Intent intent = new Intent(this, LedgerDisplayActivity.class);
intent.putExtra("id", adapterLedgerResultList.get(position).getLedger_hash());
startActivity(intent);
//Toast.makeText(this,"Hey there, you onClicked!", Toast.LENGTH_SHORT).show();
}
public List<LedgerResult> addToadapterLedgerResultList (LedgerResult ledgerResult1){
if(adapterLedgerResultList.size() != 0) {
adapterLedgerResultList.add(ledgerResult1);
/* myWebSocketAdapter.notifyItemInserted(adapterLedgerResultList.indexOf(ledgerResult1));
webSocketRecyclerView.scrollToPosition(adapterLedgerResultList.indexOf(ledgerResult1));*/
myWebSocketAdapter.notifyItemInserted(adapterLedgerResultList.size() - 1);
//myWebSocketAdapter.notifyDataSetChanged();
webSocketRecyclerView.scrollToPosition(adapterLedgerResultList.size() - 1);
return adapterLedgerResultList;
}
else {
adapterLedgerResultList.add(ledgerResult1);
myWebSocketAdapter.notifyItemInserted(0);
//myWebSocketAdapter.notifyDataSetChanged();
return adapterLedgerResultList;
}
}
public class MySimpleClient extends WebSocketClient {
public MySimpleClient( URI serverUri , Draft draft ) {
super( serverUri, draft );
}
public MySimpleClient( URI serverURI ) {
super( serverURI );
}
public MySimpleClient( URI serverUri, Map<String, String> httpHeaders ) {
super(serverUri, httpHeaders);
}
#Override
public void onOpen( ServerHandshake handshakedata ) {
send("{\n" +
" \"id\": 1,\n" +
" \"command\": \"subscribe\",\n" +
" \"accounts\": [],\n" +
" \"streams\": [\n" +
" \"server\",\n" +
" \"ledger\"\n" +
" ]\n" +
"}");
Log.d("SearchCode", "Connection opened!");
// if you plan to refuse connection based on ip or httpfields overload: onWebsocketHandshakeReceivedAsClient
}
#Override
public void onMessage(String message) {
try {
JSONObject obj = new JSONObject(message);
Gson gson = new Gson();
LedgerResult ledgerResult = gson.fromJson(obj.toString(),LedgerResult.class);
StreamExceptionHandler lilHandler = gson.fromJson(obj.toString(),StreamExceptionHandler.class);
if(lilHandler.getBase_fee() != null){
//do nothing.
}else {
adapterLedgerResultList = addToadapterLedgerResultList(ledgerResult);
if(adapterLedgerResultList.get(0).getLedger_index() == null){
LedgerResult tmp = adapterLedgerResultList.get(0);
adapterLedgerResultList.remove(tmp);
myWebSocketAdapter.notifyItemRemoved(0);
// myWebSocketAdapter.notifyDataSetChanged();
}
else {
bindIt();
Log.d("This is obj", obj.toString());
Log.d("LedgerResult", ledgerResult.toString());
}
}
} catch (Throwable t) {
Log.e("SeachCode", "Could not parse malformed JSON: \"" + message + "\"");
}
}
#Override
public void onClose( int code, String reason, boolean remote ) {
Log.e("SearchCode: ","Connection closed by " + ( remote ? "remote peer" : "us" ) + " Code: " + code + " Reason: " + reason);
}
#Override
public void onError( Exception ex ) {
ex.printStackTrace();
}
}
}
And my adapter code MyWebSocketAdapter is here:
package com.example.menes.searchcode.Websocketing;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.menes.searchcode.R;
import java.util.List;
public class MyWebSocketAdapter extends RecyclerView.Adapter<MyWebSocketAdapter.WebSocketView> {
public interface OnItemClickListener {
void onItemClick (int position);
}
private MyWebSocketAdapter.OnItemClickListener onItemClickListener;
private Context context;
private List<LedgerResult> adapterLedgerResultList;
public MyWebSocketAdapter(Context context, List<LedgerResult> adapterLedgerResultList){
this.context = context;
this.adapterLedgerResultList = adapterLedgerResultList;
}
/*public MyWebSocketAdapter(Context context){
this.context = context;
}*/
/*public List<LedgerResult> addToadapterLedgerResultList (LedgerResult ledgerResult1){
adapterLedgerResultList.add(ledgerResult1);
if(adapterLedgerResultList.size() != 0) {
notifyItemInserted(adapterLedgerResultList.indexOf(ledgerResult1));
return adapterLedgerResultList;
}
else {
notifyItemInserted(0);
return adapterLedgerResultList;
}
}*/
public void setOnItemClickListener(MyWebSocketAdapter.OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
class WebSocketView extends RecyclerView.ViewHolder {
TextView otherThing;
TextView hashCode, textView;
public WebSocketView(View itemView) {
super(itemView);
hashCode = itemView.findViewById(R.id.hashCode);
otherThing = itemView.findViewById(R.id.otherThing);
textView = itemView.findViewById(R.id.textView);
}
}
#Override
public WebSocketView onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.in_recycler, parent, false);
return new WebSocketView(layoutView);
}
#Override
public void onBindViewHolder(WebSocketView holder, final int position) {
final WebSocketView hldr = holder;
LedgerResult row = adapterLedgerResultList.get(hldr.getAdapterPosition());
if(row.getLedger_hash() == null) {
holder.hashCode.setText("IT IS NULL");
}
else {
holder.hashCode.setText(row.getLedger_hash());
holder.hashCode.setTextColor(Color.parseColor("#239DEA"));
}
if(row.getLedger_index() == null) {
holder.otherThing.setText("IT IS NULL");
}
else {
holder.otherThing.setText(row.getLedger_index().toString());
}
if(row.getLedger_index() != null) {
String s = row.getValidated_ledgers().toString();
holder.textView.setText(s);
//holder.textView.setVisibility(View.VISIBLE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(onItemClickListener != null) {
onItemClickListener.onItemClick(hldr.getAdapterPosition());
}
}
});
}
/* #Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}*/
#Override
public int getItemCount() {
return adapterLedgerResultList.size();
}
}
My XML files which I have also checked millions of times and even re-created.
websocket_and_button_thing.xml is:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/startButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Start"
app:layout_constraintBottom_toTopOf="#+id/stopButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/myRecyclerView"
app:layout_constraintVertical_bias="1.0" />
<Button
android:id="#+id/stopButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Stop"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
<android.support.v7.widget.RecyclerView
app:layoutManager="android.support.v7.widget.LinearLayoutManager"
android:id="#+id/myRecyclerView"
android:layout_width="368dp"
android:layout_height="363dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="4dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
And finally the inside-of-recyclerView code is called in-recycler.xml and it is:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView"
android:layout_width="94dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:gravity="center_horizontal"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/hashCode" />
<TextView
android:id="#+id/hashCode"
android:layout_width="261dp"
android:layout_height="20dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/otherThing"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="#+id/otherThing"
android:layout_width="0dp"
android:layout_height="20dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="16dp"
android:layout_marginTop="16dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
</android.support.constraint.ConstraintLayout>
Anyone is able to come up with a solution why TextViews are not showed up?
From the LOG records I can get all the data From debugging, my lists are working correct as well.
Note: I used the StreamExceptionHandler class to differentiate between two stream outcomes. One is useful to me, other is not and that's why I do not do anything if I catch anything.
Plus, my custom classes are working correctly since my lists seems to be well working.
AFTER EDIT:
I changed the WebSocketActivity and adapter as such. No so much changed. But now, again strangely, I am gettin all the data. It is added to RecyclerView too, but it does not show itself until I try to scroll manually. Plus, whenever a new data is arrived, RecyclerView completely disappears, then if I scroll again, it gets back with the updated data. ANY SOLUTION after update?
Do you see this line in MyWebSocketAdapter:
holder.textView.setVisibility(View.INVISIBLE);
I guess, I found it. Since I changed the systematic and the code itself I cannot post the exact code to solve it but the key is overriding the runOnUiThread function within the button click. And you should change the RecyclerView binding and manager sets as well. Do it in a different place.
To override the runOnUiThread in an anonymous (inner) class, use this:
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
Hope this helps the future visitors.
In my app my user is entering the category and that category is stored in the FirebseDB. After storing the value in the DB the user can view the inserted value in the Spinner.
At this point all works fine.
I want user to enter only unique value .so , if user wants to enter the value which is already there he should get a Toast.
Following is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.lenovo.baicactivitytest.MainActivity">
<Spinner
android:id="#+id/sp"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<Button
android:id="#+id/add_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="70dp"
android:text="Add" />
</RelativeLayout>
Following is my inputdialogue.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
android:orientation="vertical"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="50dp">
<android.support.design.widget.TextInputLayout
android:id="#+id/nameLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/nameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:hint= "Name" />
</android.support.design.widget.TextInputLayout>
<Button android:id="#+id/saveBtn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save"
android:clickable="true"
android:background="#color/colorAccent"
android:layout_marginTop="40dp"
android:textColor="#android:color/white"/>
</LinearLayout>
</LinearLayout>
Spacecraft.java
package com.example.lenovo.baicactivitytest;
/**
* Created by LENOVO on 29-12-2017.
*/
public class Spacecraft {
String name;
public Spacecraft() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
FirebaseHelper
package com.example.lenovo.baicactivitytest;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseException;
import com.google.firebase.database.DatabaseReference;
import java.util.ArrayList;
/**
* Created by LENOVO on 29-12-2017.
*/
public class FirebaseHelper {
DatabaseReference db;
Boolean saved = null;
public FirebaseHelper(DatabaseReference db) {
this.db = db;
}
//SAVE
public Boolean save(Spacecraft spacecraft)
{
if(spacecraft==null)
{
saved=false;
}else
{
try
{
db.child("Spacecraft").push().setValue(spacecraft);
saved=true;
}catch (DatabaseException e)
{
e.printStackTrace();
saved=false;
}
}
return saved;
}
//READ
public ArrayList<String> retrieve()
{
final ArrayList<String> spacecrafts=new ArrayList<>();
db.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot,spacecrafts);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot,spacecrafts);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return spacecrafts;
}
private void fetchData(DataSnapshot snapshot,ArrayList<String> spacecrafts)
{
spacecrafts.clear();
for (DataSnapshot ds:snapshot.getChildren())
{
String name=ds.getValue(Spacecraft.class).getName();
spacecrafts.add(name);
}
}
}
MainActivity.java
package com.example.lenovo.baicactivitytest;
import android.app.Dialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity {
DatabaseReference db;
FirebaseHelper helper;
private Button madd_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner sp =(Spinner) findViewById(R.id.sp);
//SETUP FB
db= FirebaseDatabase.getInstance().getReference();
helper = new FirebaseHelper(db);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,helper.retrieve());
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
madd_btn = (Button) findViewById(R.id.add_btn);
madd_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
displayInputDialog();
}
});
}
//DISPLAY INPUT DILAOG
private void displayInputDialog()
{
Dialog d=new Dialog(this);
d.setTitle("Firebase database");
d.setContentView(R.layout.inputdialog);
final EditText nameTxt= (EditText) d.findViewById(R.id.nameEditText);
Button saveBtn = (Button) d.findViewById(R.id.saveBtn);
//SAVE
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//GET DATA
String name=nameTxt.getText().toString();
//set data
Spacecraft s = new Spacecraft();
s.setName(name);
//SAVE
if(name != null && name.length()>0)
{
if(helper.save(s))
{
nameTxt.setText("");
}
}else
{
Toast.makeText(MainActivity.this, "Name Cannot Be Empty", Toast.LENGTH_SHORT).show();
}
}
});
d.show();
}
}
Can do this:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Category");
ref.orderByChild("categoryname").equalTo(name).addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot){
if(dataSnapshot.exist()) {
Toast.makeText(MainActivity.this, "Name already exists", Toast.LENGTH_SHORT).show();
}
}
Can do the above, it will search in the Category node in the db, and if it exists then it will give you the Toast message.
MainActivity.java
package com.example.intel.dualboot;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements StatusAsyncTask.StatusAsyncTaskListener, SwipeRefreshLayout.OnRefreshListener, MainActivityListener {
private static final String TAG = "db::MainActivity";
/* public static final int ACT_INSTALL_ROM = 1;
public static final int ACT_CHANGE_PAGE = 2;
public static final int ACT_SELECT_ICON = 3;
public static final int ACT_UNINSTALL_ROM = 4;
public static final String INTENT_EXTRA_SHOW_ROM_LIST = "show_rom_list";*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(Build.VERSION.SDK_INT == 20) {
showDeprecatedLAlert();
return;
}
setContentView(R.layout.activity_main);
// This activity is using different background color, which would cause overdraw
// of the whole area, so disable the default background
getWindow().setBackgroundDrawable(null);
Utils.installHttpCache(this);
PreferenceManager.setDefaultValues(this, R.xml.settings, false);
m_srLayout = (InSwipeRefreshLayout)findViewById(R.id.refresh_layout);
m_srLayout.setOnRefreshListener(this);
m_curFragment = -1;
m_fragmentTitles = getResources().getStringArray(R.array.main_fragment_titles);
m_drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
m_drawerList = (ListView) findViewById(R.id.left_drawer);
String[] fragmentClsNames = new String[MainFragment.MAIN_FRAG_CNT];
for(int i = 0; i < fragmentClsNames.length; ++i)
fragmentClsNames[i] = MainFragment.getFragmentClass(i).getName();
m_fragments = new MainFragment[MainFragment.MAIN_FRAG_CNT];
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction t = fragmentManager.beginTransaction();
for(int i = 0; i < m_fragments.length; ++i) {
m_fragments[i] = (MainFragment)fragmentManager.findFragmentByTag(fragmentClsNames[i]);
if(m_fragments[i] == null) {
m_fragments[i] = MainFragment.newFragment(i);
t.add(R.id.content_frame, m_fragments[i], fragmentClsNames[i]);
}
t.hide(m_fragments[i]);
}
t.commit();
// Set the adapter for the list view
m_drawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list, m_fragmentTitles));
// Set the list's click listener
m_drawerList.setOnItemClickListener(new DrawerItemClickListener());
m_drawerTitle = getText(R.string.app_name);
m_drawerToggle = new ActionBarDrawerToggle(
this, m_drawerLayout, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(m_title);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(m_drawerTitle);
}
};
m_drawerLayout.setDrawerListener(m_drawerToggle);
final ActionBar bar = getSupportActionBar();
if(bar != null) {
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
}
/* if (getIntent().hasExtra(INTENT_EXTRA_SHOW_ROM_LIST) &&
getIntent().getBooleanExtra(INTENT_EXTRA_SHOW_ROM_LIST, false)) {
getIntent().removeExtra(INTENT_EXTRA_SHOW_ROM_LIST);
selectItem(1);
} else if(savedInstanceState != null) {
selectItem(savedInstanceState.getInt("curFragment", 0));
} else {
selectItem(0);
}*/
}
/*#Override
protected void onNewIntent(Intent i) {
super.onNewIntent(i);
if (i.hasExtra(INTENT_EXTRA_SHOW_ROM_LIST) &&
i.getBooleanExtra(INTENT_EXTRA_SHOW_ROM_LIST, false)) {
selectItem(1);
}
}*/
#Override
protected void onStop() {
super.onStop();
Utils.flushHttpCache();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curFragment", m_curFragment);
}
#Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
m_refreshItem = menu.findItem(R.id.action_refresh);
if(!StatusAsyncTask.instance().isComplete())
m_refreshItem.setEnabled(false);
return true;
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
if(position < 0 || position >= m_fragments.length) {
Log.e(TAG, "Invalid fragment index " + position);
return;
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction t = fragmentManager.beginTransaction();
if(m_curFragment != -1)
t.hide(m_fragments[m_curFragment]);
t.show(m_fragments[position]);
t.commit();
m_curFragment = position;
// Highlight the selected item, update the title, and close the drawer
m_drawerList.setItemChecked(position, true);
setTitle(m_fragmentTitles[position]);
m_drawerLayout.closeDrawer(m_drawerList);
}
#Override
public void setTitle(CharSequence title) {
m_title = title;
getSupportActionBar().setTitle(m_title);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
if(m_drawerToggle != null)
m_drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(m_drawerToggle != null)
m_drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem it) {
if (m_drawerToggle.onOptionsItemSelected(it))
return true;
switch(it.getItemId()) {
case R.id.action_refresh:
refresh(false);
return true;
case R.id.action_reboot:
{
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Reboot")
.setCancelable(true)
.setNegativeButton("Cancel", null)
.setItems(R.array.reboot_options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i) {
case 0: Utils.reboot(""); break;
case 1: Utils.reboot("recovery"); break;
case 2: Utils.reboot("bootloader"); break;
}
}
})
.create().show();
return true;
}
default:
return false;
}
}
public void startRefresh(boolean notifyRefreshLayout) {
if(notifyRefreshLayout)
m_srLayout.setRefreshing(true);
if(m_refreshItem != null)
m_refreshItem.setEnabled(false);
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].startRefresh();
StatusAsyncTask.instance().setListener(this);
StatusAsyncTask.instance().execute();
}
#Override
public void refresh(boolean b) {
refresh(true);
}
#Override
public void setRefreshComplete() {
m_srLayout.setRefreshing(false);
if(m_refreshItem != null)
m_refreshItem.setEnabled(true);
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].setRefreshComplete();
}
#Override
public void onFragmentViewCreated() {
if(++m_fragmentViewsCreated == m_fragments.length) {
// postDelayed because SwipeRefresher view ignores
// setRefreshing call otherwise
m_srLayout.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = getIntent();
if(i == null || !i.getBooleanExtra("force_refresh", false)) {
startRefresh(true);
} else {
i.removeExtra("force_refresh");
refresh(false);
}
}
}, 1);
}
}
#Override
public void onFragmentViewDestroyed() {
--m_fragmentViewsCreated;
}
#Override
public void addScrollUpListener(InSwipeRefreshLayout.ScrollUpListener l) {
m_srLayout.addScrollUpListener(l);
}
#Override
public void onStatusTaskFinished(StatusAsyncTask.Result res) {
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].onStatusTaskFinished(res);
}
#Override
public void onRefresh() {
refresh(false);
}
#TargetApi(20)
private void showDeprecatedLAlert() {
SpannableString msg = new SpannableString("Android Developer preview has bugs");
Linkify.addLinks(msg, Linkify.ALL);
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Unsupported Android version")
.setCancelable(false)
.setMessage(msg)
.setNegativeButton("Exit Application", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
AlertDialog d = b.create();
d.show();
TextView msgView = (TextView)d.findViewById(android.R.id.message);
msgView.setMovementMethod(LinkMovementMethod.getInstance());
}
private DrawerLayout m_drawerLayout;
private ListView m_drawerList;
private String[] m_fragmentTitles;
private MainFragment[] m_fragments;
private int m_curFragment;
private CharSequence m_title;
private ActionBarDrawerToggle m_drawerToggle;
private CharSequence m_drawerTitle;
private MenuItem m_refreshItem;
private int m_fragmentViewsCreated;
private InSwipeRefreshLayout m_srLayout;
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<com.example.intel.dualboot.InSwipeRefreshLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/refresh_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<FrameLayout android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.example.intel.dualboot.InSwipeRefreshLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="#dimen/lviewdimen"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111" />
</android.support.v4.widget.DrawerLayout>
Stack Trace
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.intel.dualboot, PID: 23319
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.intel.dualboot/com.example.intel.dualboot.MainActivity}:
java.lang.NullPointerException: Attempt to write to field
'android.app.FragmentManagerImpl
android.app.Fragment.mFragmentManager' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2330)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5273)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Caused by: java.lang.NullPointerException: Attempt to write to field
'android.app.FragmentManagerImpl
android.app.Fragment.mFragmentManager' on a null object reference
at android.app.BackStackRecord.doAddOp(BackStackRecord.java:469)
at android.app.BackStackRecord.add(BackStackRecord.java:464)
at com.example.intel.dualboot.MainActivity.onCreate(MainActivity.java:78)
at android.app.Activity.performCreate(Activity.java:6041)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1109)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2283)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5273)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
replace
com.exmaple.intel.dualboot.InSwipeRefreshLayout
with
android.support.v4.widget.SwipeRefreshLayout
in your xml file,
as the com.exmaple.intel.dualboot.InSwipeRefreshLayout class is not defined
com.exmaple.intel.dualboot.InSwipeRefreshLayout
Check this path if it is correct in your xml.It seems the path of "InSwipeRefreshLayout" is not corect
in your xml
<?xml version="1.0" encoding="utf-8"?><android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<com.exmaple.intel.dualboot.InSwipeRefreshLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/refresh_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<FrameLayout android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.exmaple.intel.dualboot.InSwipeRefreshLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="#dimen/lviewdimen"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111" />
</android.support.v4.widget.DrawerLayout>
the com.exmaple.intel.dualboot.InSwipeRefreshLayout has that spelling of "exmaple", it should be example.
The posted layout working fine for me.Please check the package name properly com.example.intel.dualboot.InSwipeRefreshLayout whether exist or not and clean and build the project.
I have a fragment class in with I am having few fragment tabs. each of them are opening another dedicated fragment. but I want to change one fragment to open an activity class. I have gone through many examples but didn't the problem solve. everytime my application goes crashed.
here is my fragment class.
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.appdupe.flamer.LoginUsingFacebook;
import com.appdupe.flamer.LoginUsingFacebook.BackGroundTaskForFetchingDataFromFaceBook;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.androidquery.AQuery;
import com.androidquery.callback.ImageOptions;
import com.appdupe.androidpushnotifications.ChatActivity;
import com.appdupe.flamer.QuestionsActivity;
import com.appdupe.flamer.pojo.LikeMatcheddataForListview;
import com.appdupe.flamer.pojo.LikedMatcheData;
import com.appdupe.flamer.pojo.Likes;
import com.appdupe.flamer.utility.AlertDialogManager;
import com.appdupe.flamer.utility.AppLog;
import com.appdupe.flamer.utility.ConnectionDetector;
import com.appdupe.flamer.utility.Constant;
import com.appdupe.flamer.utility.ScalingUtilities;
import com.appdupe.flamer.utility.ScalingUtilities.ScalingLogic;
import com.appdupe.flamer.utility.SessionManager;
import com.appdupe.flamer.utility.Ultilities;
import com.appdupe.flamer.utility.Utility;
import com.appdupe.flamerchat.db.DatabaseHandler;
import com.appdupe.flamernofb.R;
import com.google.gson.Gson;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.OnOpenListener;
public class MainActivity extends SherlockFragmentActivity implements
OnClickListener, OnOpenListener {
// MainLayout mLayout;
private static final String TAG = "MainActivity";
private ListView matcheslistview;
Button btMenu;
private Button buttonRightMenu;
TextView tvTitle;
private Typeface topbartextviewFont;
private Editor editor;
private SharedPreferences preferences;
private EditText etSerchFriend;
double mLatitude = 0;
double mLongitude = 0;
double dLatitude = 0;
double dLongitude = 0;
// private Session.StatusCallback statusCallback = new
// SessionStatusCallback();
private Dialog mdialog;
// private boolean usersignup = false;
private boolean isProfileclicked = false;
private ArrayList<LikeMatcheddataForListview> arryList;
private MatchedDataAdapter adapter;
private ImageView profileimage;
private LinearLayout profilelayout, homelayout, messages, settinglayout,
invitelayout, questionLayout;
public SlidingMenu menu;
private boolean flagforHome, flagForProfile, flagForsetting;
// private AQuery aQuery;
private ImageOptions options;
private ConnectionDetector cd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// mLayout = (MainLayout)
// this.getLayoutInflater().inflate(R.layout.slidmenuxamplemainactivity,
// null);
// setContentView(mLayout);
cd = new ConnectionDetector(this);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
editor = preferences.edit();
// aQuery = new AQuery(this);
options = new ImageOptions();
options.fileCache = true;
options.memCache = true;
setContentView(R.layout.slidmenuxamplemainactivity);
if (preferences.getBoolean(Constant.PREF_ISFIRST, true)) {
editor.putBoolean(Constant.PREF_ISFIRST, false);
editor.commit();
//startActivity(new Intent(this, QuestionsActivity.class));
}
tvTitle = (TextView) findViewById(R.id.activity_main_content_title);
topbartextviewFont = Typeface.createFromAsset(getAssets(),
"fonts/HelveticaLTStd-Light.otf");
tvTitle.setTypeface(topbartextviewFont);
tvTitle.setTextColor(Color.rgb(255, 255, 255));
tvTitle.setTextSize(20);
menu = new SlidingMenu(this);
menu.setMode(SlidingMenu.LEFT_RIGHT);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
menu.setShadowWidthRes(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
menu.setFadeDegree(0.35f);
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
Log.d(TAG, "onCreate before add menu ");
menu.setMenu(R.layout.leftmenu);
menu.setSecondaryMenu(R.layout.rightmenu);
Log.d(TAG, "onCreate add menu ");
menu.setSlidingEnabled(true);
Log.d(TAG, "onCreate finish");
// search
etSerchFriend = (EditText) menu
.findViewById(R.id.et_serch_right_side_menu);
// btnSerch = (Button) menu.findViewById(R.id.btn_serch_right_side);
View leftmenuview = menu.getMenu();
View rightmenuview = menu.getSecondaryMenu();
initLayoutComponent(leftmenuview, rightmenuview);
menu.setSecondaryOnOpenListner(this);
// lvMenuItems = getResources().getStringArray(R.array.menu_items);
// lvMenu.setAdapter(new
// ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,
// lvMenuItems));
matcheslistview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// logDebug("setOnItemClickListener onItemClick arg2 "+arg2);
LikeMatcheddataForListview matcheddataForListview = (LikeMatcheddataForListview) arg0
.getItemAtPosition(arg2);
String faceboolid = matcheddataForListview.getFacebookid();
// logDebug(" background setOnItemClickListener onItemClick friend facebook id faceboolid "+faceboolid);
// logDebug(" background setOnItemClickListener onItemClick user facebook id faceboolid"+new
// SessionManager(MainActivity.this).getFacebookId());
Bundle mBundle = new Bundle();
mBundle.putString(Constant.FRIENDFACEBOOKID, faceboolid);
mBundle.putString(Constant.CHECK_FOR_PUSH_OR_NOT, "1");
Intent mIntent = new Intent(MainActivity.this,
ChatActivity.class);
mIntent.putExtras(mBundle);
startActivity(mIntent);
menu.toggle();
}
});
buttonRightMenu = (Button) findViewById(R.id.button_right_menu);
btMenu = (Button) findViewById(R.id.button_menu);
btMenu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Show/hide the menu
toggleMenu(v);
}
});
try {
profilelayout.setOnClickListener(this);
homelayout.setOnClickListener(this);
messages.setOnClickListener(this);
settinglayout.setOnClickListener(this);
invitelayout.setOnClickListener(this);
questionLayout.setOnClickListener(this);
} catch (Exception e) {
AppLog.handleException("oncreate Exception ", e);
}
// Bundle extras = getIntent().getExtras();
System.out.println("Get Intent done");
try {
FragmentManager fm = MainActivity.this.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
FindMatches fragment = new FindMatches();
ft.add(R.id.activity_main_content_fragment, fragment);
tvTitle.setText(getResources().getString(R.string.app_name));
ft.commit();
setProfilePick(profileimage);
} catch (Exception e) {
AppLog.handleException("onCreate Exception ", e);
}
Ultilities mUltilities = new Ultilities();
int imageHeightAndWidht[] = mUltilities
.getImageHeightAndWidthForAlubumListview(this);
arryList = new ArrayList<LikeMatcheddataForListview>();
adapter = new MatchedDataAdapter(this, arryList, imageHeightAndWidht);
matcheslistview.setAdapter(adapter);
// final SessionManager sessionManager = new SessionManager(this);
buttonRightMenu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (isProfileclicked) {
Intent mIntent = new Intent(MainActivity.this,
EditProfileNew.class);
startActivity(mIntent);
} else {
toggleRightMenu(v);
}
}
});
initSerchData();
}
private void initSerchData() {
etSerchFriend.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s.toString().trim());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void setMenuTouchFullScreenEnable(boolean isEnable) {
if (isEnable) {
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
} else {
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
}
}
#Override
public void onOpen() {
AppLog.Log(TAG, "onOpen");
findLikedMatched();
}
#Override
protected void onResume() {
super.onResume();
AppLog.Log(TAG, " MainActivity onResume called");
}
private void setProfilePick(final ImageView userProfilImage) {
final Ultilities mUltilities = new Ultilities();
new Thread(new Runnable() {
#Override
public void run() {
final Bitmap bitmapimage = Utility.getBitmapFromURL(preferences
.getString(Constant.PREF_PROFILE_IMAGE_ONE, ""));
runOnUiThread(new Runnable() {
#Override
public void run() {
AppLog.Log(
TAG,
"Profile Image Url:"
+ preferences
.getString(
Constant.PREF_PROFILE_IMAGE_ONE,
""));
Bitmap cropedBitmap = null;
ScalingUtilities mScalingUtilities = new ScalingUtilities();
Bitmap mBitmap = null;
if (bitmapimage != null) {
cropedBitmap = mScalingUtilities
.createScaledBitmap(bitmapimage, 80, 80,
ScalingLogic.CROP);
bitmapimage.recycle();
mBitmap = mUltilities.getCircleBitmap(cropedBitmap,
1);
cropedBitmap.recycle();
userProfilImage.setImageBitmap(mBitmap);
// aQuery.id(userProfilImage).image(mBitmap);
} else {
}
}
});
}
}).start();
}
private void initLayoutComponent(View leftmenu, View rightmenu) {
matcheslistview = (ListView) rightmenu
.findViewById(R.id.menu_right_ListView);
profileimage = (ImageView) leftmenu.findViewById(R.id.profileimage);
profilelayout = (LinearLayout) leftmenu
.findViewById(R.id.profilelayout);
homelayout = (LinearLayout) leftmenu.findViewById(R.id.homelayout);
messages = (LinearLayout) leftmenu.findViewById(R.id.messages);
settinglayout = (LinearLayout) leftmenu
.findViewById(R.id.settinglayout);
invitelayout = (LinearLayout) leftmenu.findViewById(R.id.invitelayout);
/*questionLayout = (LinearLayout) leftmenu
.findViewById(R.id.questionLayout);*///devraj
}
private void findLikedMatched() {
AppLog.Log(TAG, "findLikedMatched");
String params[] = { preferences.getString(Constant.FACEBOOK_ID, "") };
new BackgroundTaskForFindLikeMatched().execute(params);
}
private class BackgroundTaskForFindLikeMatched extends
AsyncTask<String, Void, Void> {
private Ultilities mUltilities = new Ultilities();
private List<NameValuePair> getuserparameter;
private String likedmatchedata;
private LikedMatcheData matcheData;
private ArrayList<Likes> likesList;
private LikeMatcheddataForListview matcheddataForListview;
DatabaseHandler mDatabaseHandler = new DatabaseHandler(
MainActivity.this);
private boolean isResponseSuccess = true;
#Override
protected Void doInBackground(String... params) {
try {
File appDirectory = mUltilities
.createAppDirectoy(getResources().getString(
R.string.appdirectory));
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground appDirectory "
+ appDirectory);
File _picDir = new File(appDirectory, getResources().getString(
R.string.imagedirematchuserdirectory));
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground ");
getuserparameter = mUltilities.getUserLikedParameter(params);
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground getuserparameter "
+ getuserparameter);
likedmatchedata = mUltilities.makeHttpRequest(
Constant.getliked_url, Constant.methodeName,
getuserparameter);
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground likedmatchedata "
+ likedmatchedata);
Gson gson = new Gson();
matcheData = gson.fromJson(likedmatchedata,
LikedMatcheData.class);
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground matcheData "
+ matcheData);
if (matcheData.getErrFlag() == 0) {
likesList = matcheData.getLikes();
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground likesList "
+ likesList);
if (arryList != null) {
arryList.clear();
}
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground likesList sized "
+ likesList.size());
for (int i = 0; i < likesList.size(); i++) {
matcheddataForListview = new LikeMatcheddataForListview();
String userName = likesList.get(i).getfName();
String facebookid = likesList.get(i).getFbId();
String picturl = likesList.get(i).getpPic();
int falg = likesList.get(i).getFlag();
String latd = likesList.get(i).getLadt();
matcheddataForListview.setFacebookid(facebookid);
matcheddataForListview.setUserName(userName);
matcheddataForListview.setImageUrl(picturl);
matcheddataForListview.setFlag("" + falg);
matcheddataForListview.setladt(latd);
File imageFile = mUltilities.createFileInSideDirectory(
_picDir, userName + facebookid + ".jpg");
Utility.addBitmapToSdCardFromURL(likesList.get(i)
.getpPic().replaceAll(" ", "%20"), imageFile);
matcheddataForListview.setFilePath(imageFile
.getAbsolutePath());
if (!preferences.getString(Constant.FACEBOOK_ID, "")
.equals(facebookid)) {
arryList.add(matcheddataForListview);
}
}
DatabaseHandler mDatabaseHandler = new DatabaseHandler(
MainActivity.this);
ArrayList<LikeMatcheddataForListview> arryListtem = mDatabaseHandler
.getUserFindMatch();
AppLog.Log(TAG, "arryListtem " + arryListtem);
if (arryListtem != null && arryListtem.size() > 0) {
AppLog.Log(TAG, "arryList size " + arryListtem.size());
arryList.clear();
arryList.addAll(arryListtem);
mUltilities.showImage
}
}
// "errNum": "50",
// "errFlag": "1",
// "errMsg": "Sorry, no matches found!"
else if (matcheData.getErrFlag() == 1) {
ArrayList<LikeMatcheddataForListview> arryListtem = mDatabaseHandler
.getUserFindMatch();
AppLog.Log(TAG, "arryListtem " + arryListtem);
if (arryListtem != null && arryListtem.size() > 0) {
AppLog.Log(TAG, "arryList size " + arryListtem.size());
arryList.clear();
arryList.addAll(arryListtem);
}
} else {
}
} catch (Exception e) {
AppLog.handleException(
"BackgroundTaskForFindLikeMatched doInBackground Exception ",
e);
isResponseSuccess = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
AppLog.Log(TAG, "BackgroundTaskForFindLikeMatched onPostExecute ");
try {
mdialog.dismiss();
} catch (Exception e) {
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched onPostExecute Exception "
+ e);
}
if (!isResponseSuccess) {
AlertDialogManager.errorMessage(MainActivity.this, "Alert",
"Request timeout");
}
adapter.notifyDataSetChanged();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
AppLog.Log(TAG, "BackgroundTaskForFindLikeMatched onPreExecute ");
try {
mdialog = mUltilities.GetProcessDialog(MainActivity.this);
mdialog.setCancelable(false);
mdialog.show();
} catch (Exception e) {
AppLog.handleException(
"BackgroundTaskForFindLikeMatched onPreExecute Exception ",
e);
}
}
}
private class MatchedDataAdapter extends
ArrayAdapter<LikeMatcheddataForListview> {
private AQuery aQuery;
private Activity mActivity;
private LayoutInflater mInflater;
private SessionManager sessionManager;
public MatchedDataAdapter(Activity context,
List<LikeMatcheddataForListview> objects,
int imageHeigthAndWidth[]) {
super(context, R.layout.matchedlistviewitem, objects);
mActivity = context;
mInflater = (LayoutInflater) mActivity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// this.imageHeigthAndWidth=imageHeigthAndWidth;
sessionManager = new SessionManager(context);
aQuery = new AQuery(context);
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public LikeMatcheddataForListview getItem(int position) {
return super.getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.matchedlistviewitem,
null);
holder.imageview = (ImageView) convertView
.findViewById(R.id.userimage);
holder.textview = (TextView) convertView
.findViewById(R.id.userName);
holder.lastMasage = (TextView) convertView
.findViewById(R.id.lastmessage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textview.setId(position);
holder.imageview.setId(position);
holder.lastMasage.setId(position);
holder.textview.setText(getItem(position).getUserName());
aQuery.id(holder.imageview).image(getItem(position).getImageUrl());
try {
holder.lastMasage.setText(sessionManager
.getLastMessage(getItem(position).getFacebookid()));
} catch (Exception e) {
AppLog.handleException(TAG + " getView Exception ", e);
}
return convertView;
}
class ViewHolder {
ImageView imageview;
TextView textview;
TextView lastMasage;
}
}
public void toggleMenu(View v) {
menu.toggle();
}
public void toggleRightMenu(View v) {
menu.showSecondaryMenu();
}
#Override
public void onBackPressed() {
if (menu.isMenuShowing()) {
menu.toggle();
} else if (menu.isSecondaryMenuShowing()) {
menu.showSecondaryMenu();
} else {
super.onBackPressed();
}
}
#Override
public void onStop() {
super.onStop();
if (mdialog != null) {
mdialog.dismiss();
mdialog = null;
}
}
#Override
protected void onDestroy() {
if (mdialog != null && mdialog.isShowing()) {
mdialog.dismiss();
}
super.onDestroy();
}
#Override
public void onClick(View v) {
FragmentManager fm = MainActivity.this.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment fragment = null;
if (v.getId() == R.id.homelayout) {
if (!cd.isConnectingToInternet()) {
Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
return;
}
if (flagforHome) {
menu.toggle();
return;
} else {
fragment = new FindMatches();
buttonRightMenu
.setBackgroundResource(R.drawable.selector_for_message_button);
tvTitle.setText(getResources().getString(R.string.app_name));
flagforHome = true;
flagForProfile = false;
flagForsetting = false;
isProfileclicked = false;
if (fragment != null) {
ft.replace(R.id.activity_main_content_fragment, fragment);
ft.commit();
}
menu.toggle();
}
} else if (v.getId() == R.id.profilelayout) {
if (!cd.isConnectingToInternet()) {
Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
return;
}
if (flagForProfile) {
menu.toggle();
return;
} else {
buttonRightMenu.setBackgroundResource(R.drawable.edit_btn);
isProfileclicked = true;
fragment = new UserProfile();
tvTitle.setText(getResources().getString(R.string.myprofile));
flagforHome = false;
flagForProfile = true;
flagForsetting = false;
if (fragment != null) {
ft.replace(R.id.activity_main_content_fragment, fragment);
ft.commit();
}
menu.toggle();
}
}
else if (v.getId() == R.id.settinglayout) {
if (!cd.isConnectingToInternet()) {
Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
return;
}
if (flagForsetting) {
menu.toggle();
return;
} else {
buttonRightMenu
.setBackgroundResource(R.drawable.selector_for_message_button);
tvTitle.setText(getResources().getString(R.string.settings));
fragment = new SettingActivity();
flagforHome = false;
flagForProfile = false;
flagForsetting = true;
flagForInvite=false;
isProfileclicked = false;
/*if (fragment != null) {
ft.replace(R.id.activity_main_content_fragment, fragment);
ft.commit();
// tvTitle.setText(selectedItem);
}*/
menu.toggle();
/*Intent setIntent = new Intent(getApplicationContext(),Setting2.class);
startActivity(setIntent);*/
}
}
///devraj
else if (v.getId() == R.id.messages) {
if (!cd.isConnectingToInternet()) {
Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
return;
}
toggleRightMenu(v);
} /*else if (v.getId() == R.id.questionLayout) {
if (!cd.isConnectingToInternet()) {
Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
return;*/
/*}
menu.toggle();
Intent questionIntent = new Intent(this, QuestionsActivity.class);
startActivity(questionIntent);*/
//}
else if (v.getId() == R.id.invitelayout) {
if (!cd.isConnectingToInternet()) {
Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
return;
}
// Change by Dilavar
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent
.putExtra(
Intent.EXTRA_TEXT,
"I am using Flamer App ! Why don't you try it out...\nInstall Flamer now !\nhttps://play.google.com/store/apps/details?id=com.appdupe.flamernofb");
sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
" Flamer App !");
sendIntent.setType("message/rfc822"); //
sendIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
new String[] { " info#appdupe.com" });
startActivity(Intent
.createChooser(sendIntent, "Send mail using..."));
}
/*settinglayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent mintent = new Intent(getApplicationContext(),Setting2.class);
startActivity(mintent);
}
});*/
}
}
I want Setting tab to open a new activity not fragment that is Setting2
here is my activity class that I have to open
import android.app.Activity;
import android.os.Bundle;
public class Setting2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.setting2);
}
}
Here is my layout , I am posting it here as it so long and don't have permission to post more lines in question.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#088A08" >
<Button
android:id="#+id/button_menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:background="#drawable/selector_for_menu_button"
android:onClick="toggleMenu" />
<TextView
android:id="#+id/activity_main_content_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Toker" />
<Button
android:id="#+id/button_right_menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:background="#drawable/selector_for_message_button"
android:onClick="rightmenu" />
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="150dp"
android:background="#088A08" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#088A08" >
<ImageView
android:id="#+id/imagev1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/btn_add_photo"
android:gravity="center_horizontal" />
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout1"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:background="#088A08"
android:gravity="center_horizontal"
android:text="View My Profile" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="5.0">
<RelativeLayout
android:id="#+id/lin1"
android:layout_width="fill_parent"
android:layout_weight="1.0"
android:background="#ffffff"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_alignTop="#+id/imageView1"
android:layout_marginBottom="9dp"
android:layout_marginLeft="21dp"
android:layout_toRightOf="#+id/imageView1"
android:text="Discovery Settings"
android:textSize="12dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_alignLeft="#+id/textView1"
android:text="Change who you see" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="#drawable/pref" />
<Button
android:id="#+id/morebtn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView1"
android:layout_marginRight="20dp"
android:background="#drawable/more" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#color/black"
android:orientation="horizontal"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_weight="1.0"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="#drawable/settings" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imageView2"
android:layout_marginLeft="23dp"
android:layout_toRightOf="#+id/imageView2"
android:text="App Settings"
android:textSize="12dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView2"
android:layout_alignLeft="#+id/textView3"
android:text="Notification and Resource" />
<Button
android:id="#+id/morebtn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView3"
android:layout_marginRight="20dp"
android:background="#drawable/more" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#color/black"
android:orientation="horizontal"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_weight="1.0"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="#drawable/filter" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView3"
android:layout_marginLeft="23dp"
android:layout_toRightOf="#+id/imageView3"
android:text="What are you into" />
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView4"
android:layout_alignTop="#+id/imageView3"
android:text="Your Interest"
android:textSize="12dp" />
<Button
android:id="#+id/morebtn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView8"
android:layout_marginRight="20dp"
android:background="#drawable/more" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#color/black"
android:orientation="horizontal"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_weight="1.0"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="#drawable/reachout" />
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView5"
android:layout_marginLeft="27dp"
android:layout_toRightOf="#+id/imageView5"
android:text="We want to hear it all" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView6"
android:layout_alignTop="#+id/imageView5"
android:text="Get in Touch"
android:textSize="12dp" />
<Button
android:id="#+id/morebtn4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView7"
android:layout_marginRight="20dp"
android:background="#drawable/more" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#color/black"
android:orientation="horizontal"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_weight="1.0"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="#drawable/share" />
<Button
android:id="#+id/morebtn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView5"
android:layout_marginRight="20dp"
android:background="#drawable/more" />
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/morebtn5"
android:layout_marginLeft="27dp"
android:layout_toRightOf="#+id/imageView4"
android:text="Help us spread the world" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView9"
android:layout_alignTop="#+id/imageView4"
android:text="Tell Your Friends"
android:textSize="12dp" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#color/black"
android:orientation="horizontal"/>
</LinearLayout>
</LinearLayout>
Step 1
- declare your activity inside of the manifest
Step 2
- starActivity(new Intent(getAcivity(), MyClass.class));
Step 3
- post your logcat if this didn't help while it should !
Edit: the issue seems that you are not setting a height to your layouts, base on your layout that you posted you have five layouts that are missing android:layout_height please add that and force close shall be gone.
I have to call multiple services in background for a project in android app.
In each services i have to call separate web service and get some data and process it with local sqlite database. I am able to call each service separately and can manipulate its result with local database.
But not able to call all services in a sequence.
my code is as below:
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Timer timer = new Timer();
final SyncTableUsers syncUserObj = new SyncTableUsers(LocalService.this);
final SyncTableVehicles syncVehicleObj = new SyncTableVehicles(this);
final SyncTableLicenses syncLicenseObj = new SyncTableLicenses(this);
final SyncTableTags syncTagObj = new SyncTableTags(this);
final SyncTableTagMappings syncTagMapObj = new SyncTableTagMappings(this);
final SyncTableAddresses syncAddressObj = new SyncTableAddresses(this);
final SyncTableDispatches syncDispatchObj = new SyncTableDispatches(this);
final SyncEditCompany syncCompanyObj = new SyncEditCompany(LocalService.this);
final SyncEditVehicle syncEditVehicleObj = new SyncEditVehicle(LocalService.this);
final SyncEditUser syncEditUserObj = new SyncEditUser(this);
final SyncVehicleLog vLogObj = new SyncVehicleLog(LocalService.this);
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
syncUserObj.syncUserData();
syncVehicleObj.syncVehicleData();
syncLicenseObj.syncLicensesData();
syncTagObj.syncTagData();
syncTagMapObj.syncTagMappingData();
syncAddressObj.syncAddressData();
syncDispatchObj.syncDispatchData();
syncCompanyObj.syncCompanyData();
syncEditVehicleObj.syncVehicleData();
syncEditUserObj.syncUserData();
Log.i("TAG", "LogId After insert values ");
}
}
};
timer.scheduleAtFixedRate(timerTask, 10000, 180000); call after every
3 minute
super.onStart(intent, startid);
syncUserData is a method, which call web service.
I recommend you go for the AsyncTask solution. It is an easy and straightforward way of running requests or any other background tasks and calling web services using devices having latest OS virsion you must need to use AsyncTask.
It's also easy to implement e.g. onProgressUpdate if you need to show a progress bar of some sort while running your requests.
private class YourTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
//call your methods from here
//publish yor progress here..
publishProgress((int) ((i / (float) count) * 100));
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
//action after execution success or not
}
}
Use Intent Service to execute your tasks in sequence.
Check out the below link for details
https://developer.android.com/reference/android/app/IntentService.html
<uses-sdk
android:minSdkVersion="8"
tools:ignore="GradleOverrides" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Videocapture Activity - activitymain
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:id="#+id/CameraView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom"
android:orientation="vertical">
<LinearLayout
android:gravity="center_vertical"
android:background="#color/color_transparent"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:layout_width="match_parent"
android:layout_height="150dp"
android:orientation="horizontal">
<TextView
android:id="#+id/txt_cancel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Cancel"
android:layout_weight="1"
android:textSize="30dp"
android:textColor="#color/color_white" />
<CheckBox
android:button="#drawable/checkbox"
android:id="#+id/chk_videorecord"
android:layout_width="100dp"
android:layout_height="100dp"
android:textColor="#color/color_white"
android:textOff="#null"
android:textOn="#null" />
<TextView
android:id="#+id/txt_submit"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Submit"
android:textSize="30dp"
android:textColor="#color/color_white" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.VideoView;
public class VideoCapture extends Activity implements OnClickListener, SurfaceHolder.Callback {
public static final String LOGTAG = "VIDEOCAPTURE";
private MediaRecorder recorder;
private SurfaceHolder holder;
private CamcorderProfile camcorderProfile;
private Camera camera;
boolean recording = false;
boolean usecamera = true;
boolean previewRunning = false;
TextView txt_cancel, txt_submit;
CheckBox chk_videorecord;
private String str_record_file;
private Uri uri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
setContentView(R.layout.activity_main);
chk_videorecord = findViewById(R.id.chk_videorecord);
final SurfaceView cameraView = (SurfaceView) findViewById(R.id.CameraView);
txt_cancel = findViewById(R.id.txt_cancel);
txt_submit = findViewById(R.id.txt_submit);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
chk_videorecord.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (chk_videorecord.isChecked())
{
chk_videorecord.setBackgroundDrawable(getResources().getDrawable(R.drawable.img_stop_record));
recording = true;
recorder.start();
Toast.makeText(VideoCapture.this, "Recording Started", Toast.LENGTH_SHORT).show();
} else {
chk_videorecord.setBackgroundDrawable(getResources().getDrawable(R.drawable.img_start_record));
recorder.stop();
Toast.makeText(VideoCapture.this, "Recording Stop", Toast.LENGTH_SHORT).show();
if (usecamera) {
try {
camera.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
// recorder.release();
recording = false;
Log.v(LOGTAG, "Recording Stopped");
// Let's prepareRecorder so we can record again
prepareRecorder();
}
}
});
txt_cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
txt_submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
if(str_record_file!=null) {
Intent intent = new Intent(VideoCapture.this, HomeActivity.class);
intent.putExtra("str_record_file", str_record_file);
startActivity(intent);
}
}
});
}
private void prepareRecorder() {
recorder = new MediaRecorder();
recorder.setPreviewDisplay(holder.getSurface());
if (usecamera) {
camera.unlock();
recorder.setCamera(camera);
}
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
recorder.setProfile(camcorderProfile);
// This is all very sloppy
if (camcorderProfile.fileFormat == MediaRecorder.OutputFormat.THREE_GPP)
{
try {
File newFile = File.createTempFile("videocapture", ".3gp", Environment.getExternalStorageDirectory());
recorder.setOutputFile(newFile.getAbsolutePath());
str_record_file = newFile.getAbsolutePath();
Log.d("file_path", "=======>" + str_record_file);
} catch (IOException e) {
Log.v(LOGTAG, "Couldn't create file");
e.printStackTrace();
finish();
}
} else if (camcorderProfile.fileFormat == MediaRecorder.OutputFormat.MPEG_4) {
try {
File newFile = File.createTempFile("videocapture", ".mp4", Environment.getExternalStorageDirectory());
recorder.setOutputFile(newFile.getAbsolutePath());
str_record_file = newFile.getAbsolutePath();
Log.d("file_path", "=======>" + str_record_file);
} catch (IOException e) {
Log.v(LOGTAG, "Couldn't create file");
e.printStackTrace();
finish();
}
} else {
try {
File newFile = File.createTempFile("videocapture", ".mp4", Environment.getExternalStorageDirectory());
recorder.setOutputFile(newFile.getAbsolutePath());
str_record_file = newFile.getAbsolutePath();
Log.d("file_path", "=======>" + str_record_file);
} catch (IOException e) {
Log.v(LOGTAG, "Couldn't create file");
e.printStackTrace();
finish();
}
}
//recorder.setMaxDuration(50000); // 50 seconds
//recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
public void onClick(View v) {
if (recording) {
recorder.stop();
if (usecamera) {
try {
camera.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
// recorder.release();
recording = false;
Log.v(LOGTAG, "Recording Stopped");
// Let's prepareRecorder so we can record again
prepareRecorder();
} else {
recording = true;
recorder.start();
Log.v(LOGTAG, "Recording Started");
}
}
public void surfaceCreated(SurfaceHolder holder) {
Log.v(LOGTAG, "surfaceCreated");
if (usecamera) {
camera = Camera.open();
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
} catch (IOException e) {
Log.e(LOGTAG, e.getMessage());
e.printStackTrace();
}
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.v(LOGTAG, "surfaceChanged");
if (!recording && usecamera) {
if (previewRunning) {
camera.stopPreview();
}
try {
Camera.Parameters p = camera.getParameters();
p.setPreviewSize(camcorderProfile.videoFrameWidth, camcorderProfile.videoFrameHeight);
p.setPreviewFrameRate(camcorderProfile.videoFrameRate);
camera.setParameters(p);
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
} catch (IOException e) {
Log.e(LOGTAG, e.getMessage());
e.printStackTrace();
}
prepareRecorder();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v(LOGTAG, "surfaceDestroyed");
if (recording) {
recorder.stop();
recording = false;
}
recorder.release();
if (usecamera) {
previewRunning = false;
//camera.lock();
camera.release();
}
finish();
}
}
Custom Tinder
implementation 'com.mindorks:placeholderview:0.7.1'
implementation 'com.android.support:cardview-v7:25.3.1'
implementation 'com.github.bumptech.glide:glide:3.7.0'
implementation 'com.google.code.gson:gson:2.7'
<string-array name="arry_card">
<item>Sofia</item>
<item>Roma</item>
<item>Zoya</item>
</string-array>
<color name="colorPrimary">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>
<color name="white">#FFFFFF</color>
<color name="grey">#757171</color>
activity_main
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/grey">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_gravity="bottom"
android:gravity="center"
android:orientation="horizontal">
<ImageButton
android:id="#+id/rejectBtn"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/ic_cancel"/>
<ImageButton
android:id="#+id/acceptBtn"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="30dp"
android:background="#drawable/ic_heart"/>
</LinearLayout>
<com.mindorks.placeholderview.SwipePlaceHolderView
android:id="#+id/swipeView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
tinder_card_view
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="350dp"
android:layout_height="425dp"
android:layout_marginBottom="50dp"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:orientation="vertical"
android:background="#color/white"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
app:cardCornerRadius="7dp"
app:cardElevation="4dp">
<ImageView
android:id="#+id/profileImageView"
android:scaleType="centerCrop"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="75dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="75dp"
android:orientation="vertical"
android:layout_gravity="bottom"
android:gravity="center|left"
android:paddingLeft="20dp">
<TextView
android:id="#+id/nameAgeTxt"
android:layout_width="wrap_content"
android:textColor="#color/colorPrimaryDark"
android:textSize="18dp"
android:textStyle="bold"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/locationNameTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/colorPrimaryDark"
android:textSize="14dp"
android:textStyle="normal"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</FrameLayout>
tinder_swipe_in_msg_view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="350dp"
android:layout_height="425dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="32sp"
android:textStyle="bold"
android:layout_margin="40dp"
android:textColor="#android:color/holo_green_light"
android:text="Accept"/>
</LinearLayout>
tinder_swipe_out_msg_view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="350dp"
android:gravity="right"
android:layout_height="425dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="32sp"
android:textStyle="bold"
android:layout_margin="40dp"
android:textColor="#android:color/holo_red_light"
android:text="Reject"/>
</LinearLayout>
Profile
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Profile {
#SerializedName("name")
#Expose
private String name;
#SerializedName("url")
#Expose
private String imageUrl;
#SerializedName("age")
#Expose
private Integer age;
#SerializedName("location")
#Expose
private String location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
TinderCard
import android.content.Context;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.mindorks.placeholderview.SwipePlaceHolderView;
import com.mindorks.placeholderview.annotations.Layout;
import com.mindorks.placeholderview.annotations.Resolve;
import com.mindorks.placeholderview.annotations.View;
import com.mindorks.placeholderview.annotations.swipe.SwipeCancelState;
import com.mindorks.placeholderview.annotations.swipe.SwipeIn;
import com.mindorks.placeholderview.annotations.swipe.SwipeInState;
import com.mindorks.placeholderview.annotations.swipe.SwipeOut;
import com.mindorks.placeholderview.annotations.swipe.SwipeOutState;
#Layout(R.layout.tinder_card_view)
public class TinderCard {
#View(R.id.profileImageView)
private ImageView profileImageView;
#View(R.id.nameAgeTxt)
private TextView nameAgeTxt;
#View(R.id.locationNameTxt)
private TextView locationNameTxt;
private Profile mProfile;
private Context mContext;
private SwipePlaceHolderView mSwipeView;
public TinderCard(Context context, Profile profile, SwipePlaceHolderView swipeView) {
mContext = context;
mProfile = profile;
mSwipeView = swipeView;
}
#Resolve
private void onResolved(){
Glide.with(mContext).load(mProfile.getImageUrl()).into(profileImageView);
nameAgeTxt.setText(mProfile.getName() + ", " + mProfile.getAge());
locationNameTxt.setText(mProfile.getLocation());
}
#SwipeOut
private void onSwipedOut(){
Log.d("EVENT", "onSwipedOut");
mSwipeView.addView(this);
}
#SwipeCancelState
private void onSwipeCancelState(){
Log.d("EVENT", "onSwipeCancelState");
}
#SwipeIn
private void onSwipeIn(){
Log.d("EVENT", "onSwipedIn");
}
#SwipeInState
private void onSwipeInState(){
Log.d("EVENT", "onSwipeInState");
}
#SwipeOutState
private void onSwipeOutState(){
Log.d("EVENT", "onSwipeOutState");
}
}
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.google.gson.Gson;
import com.mindorks.placeholderview.SwipeDecor;
import com.mindorks.placeholderview.SwipePlaceHolderView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private SwipePlaceHolderView mSwipeView;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSwipeView = (SwipePlaceHolderView) findViewById(R.id.swipeView);
mContext = getApplicationContext();
mSwipeView.getBuilder()
.setDisplayViewCount(3)
.setSwipeDecor(new SwipeDecor()
.setPaddingTop(20)
.setRelativeScale(0.01f)
.setSwipeInMsgLayoutId(R.layout.tinder_swipe_in_msg_view)
.setSwipeOutMsgLayoutId(R.layout.tinder_swipe_out_msg_view));
List<Profile> profileList = new ArrayList<>();
List<String> arrayList = Arrays.asList(getResources().getStringArray(R.array.arry_card));
for (int i = 0; i < arrayList.size(); i++) {
//Profile profile = Gson.fromJson(arrayList.get(i), Profile.class);
Profile profile = new Profile();
profile.setName(arrayList.get(i));
profile.setAge(2);
profile.setImageUrl("");
profile.setLocation("");
profileList.add(profile);
}
for (Profile profile : profileList) {
mSwipeView.addView(new TinderCard(mContext, profile, mSwipeView));
}
findViewById(R.id.rejectBtn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSwipeView.doSwipe(false);
}
});
findViewById(R.id.acceptBtn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSwipeView.doSwipe(true);
}
});
}
}