in the onCreate of activit-main i make an inistance of a class named XMPPConectio
at the constructor of the XMMPPConnection i take inistance of the activity-main and therefor i execute an Asychtask. in the progressUpdate i call triger function of activity-main. i the triger function i want to send inistance of XMPPconnectio to other activity by intent.putExtra but i get the error
Parcelable encountered IOException writing serializable object
the aim of doing all these is to have connection (when it is connected) to other activity.
please give me some sample code thank you
XMPPConectio class which implements Serializable:
public class XMPPConnectio implements Serializable {
XMPPTCPConnection connection;
String connectionMessages="";
connectionXMPP connectionXMPPAsynch;
MainActivity mainActivity;
public XMPPTCPConnection getXMPPConnectio ()
{
return connection;
}
public XMPPConnectio(MainActivity mainActivity)
{
this.mainActivity=mainActivity;
try
{
connectionXMPPAsynch =new connectionXMPP();
connectionXMPPAsynch.execute();
}
catch (Exception e)
{
}
}
class connectionXMPP extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... params) {
connection = new XMPPTCPConnection(XMPPTCPConnectionConfiguration.builder()
.setServiceName("192.168.1.6")
.setUsernameAndPassword("ehsan", "123")
.setPort(9090)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setDebuggerEnabled(true)
.setCompressionEnabled(false).build());
connection.setUseStreamManagement(true);
connection.addConnectionListener(new ConnectionListener()
{
#Override
public void connected(XMPPConnection connection) {
Log.d("connected", "yes connected successfully : ");
publishProgress();
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
Log.d("connected","yes authenticated successfully : ");
}
#Override
public void connectionClosed() {
Log.d("connected","yes connectionClosed successfully : ");
}
#Override
public void connectionClosedOnError(Exception e) {
Log.d("connected","yes connectionClosedOnError : ");
}
#Override
public void reconnectionSuccessful() {
Log.d("connected","yes reconnection successfully : ");
}
#Override
public void reconnectingIn(int seconds) {
Log.d("connected","yes reconnectingIn : ");
}
#Override
public void reconnectionFailed(Exception e) {
Log.d("connected","yes reconnectionFailed : ");
}
});
connect();
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
mainActivity.triger();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("","onPostExecute");
}
private void connect()
{
try {
connection.connect();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
}
}
}
the Activity which make instance of XMPPConectio and cause Asychtask execution
package passargad.ehsan;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.Socket;
public class MainActivity extends ActionBarActivity implements Serializable {
private Socket socket;
private String serverIpAddress = "192.168.1.6";
XMPPConnectio xmppConnectio;
XMPPTCPConnection connection;
private static final int REDIRECTED_SERVERPORT = 6789;
FastFood fastFood;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent=new Intent(this,SocketService.class);
startService(intent);
fastFood =new FastFood(this);
xmppConnectio=new XMPPConnectio(this);
}
// this is the function which is called (when connection is done ) by //onProgressUpdate of Asychtask
public void triger()
{
try {
Intent intent= new Intent(this,chat.class);
intent.putExtra("XMPP",xmppConnectio);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
this is the activity which i want to have XMPPConnectio in there but the execution never reach to this
package passargad.ehsan;
import android.app.Application;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import java.io.IOException;
public class chat extends ActionBarActivity {
XMPPConnectio xmppConnectio;
XMPPTCPConnection connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
xmppConnectio=(XMPPConnectio)getIntent().getSerializableExtra("XMPP");
Log.d("","done");
}
}
i tried to make the question crystal clear by giving all the code. as i said the goal is to have the connection in all activities when connection is connected.
thank you .
if i want to have connection object accessible in every activities one of the solutions is using bundle and send the bundle with intent. but the actual problem is not having bundle option in API level 10 (android 2.3). the other problem was ,not having the option to use serializing and putExtra for intent because XMPPTCPConnection does not implemet serializable. so i used the third option which was defining the object static.
so i changed the class XMPPConectio to this
import android.app.Application;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManager;
import org.jivesoftware.smack.chat.ChatManagerListener;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import java.io.IOException;
import java.io.Serializable;
public class XMPPConnectio {
XMPPTCPConnection connection;
String connectionMessages="";
connectionXMPP connectionXMPPAsynch;
MainActivity mainActivity;
public XMPPTCPConnection getXMPPConnectio ()
{
return connection;
}
public XMPPConnectio(MainActivity mainActivity)
{
this.mainActivity=mainActivity;
try
{
connectionXMPPAsynch =new connectionXMPP();
connectionXMPPAsynch.execute();
}
catch (Exception e)
{
}
}
class connectionXMPP extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... params) {
connection = new XMPPTCPConnection(XMPPTCPConnectionConfiguration.builder()
.setServiceName("192.168.1.6")
.setUsernameAndPassword("ehsan", "123")
.setPort(9090)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setDebuggerEnabled(true)
.setCompressionEnabled(false).build());
connection.setUseStreamManagement(true);
connection.addConnectionListener(new ConnectionListener()
{
#Override
public void connected(XMPPConnection connection) {
Log.d("connected","yes connected successfully : ");
publishProgress();
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
Log.d("connected","yes authenticated successfully : ");
}
#Override
public void connectionClosed() {
Log.d("connected","yes connectionClosed successfully : ");
}
#Override
public void connectionClosedOnError(Exception e) {
Log.d("connected","yes connectionClosedOnError : ");
}
#Override
public void reconnectionSuccessful() {
Log.d("connected","yes reconnection successfully : ");
}
#Override
public void reconnectingIn(int seconds) {
Log.d("connected","yes reconnectingIn : ");
}
#Override
public void reconnectionFailed(Exception e) {
Log.d("connected","yes reconnectionFailed : ");
}
});
connect();
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
mainActivity.triger();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("","onPostExecute");
}
private void connect()
{
try {
connection.connect();
// connection.login();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
}
}
}
the Activity which make instance of XMPPConectio and cause Asychtask execution
package passargad.ehsan;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.Socket;
public class MainActivity extends ActionBarActivity {
private Socket socket;
private String serverIpAddress = "192.168.1.6";
XMPPConnectio xmppConnectio;
public static XMPPTCPConnection connection;
private static final int REDIRECTED_SERVERPORT = 6789;
FastFood fastFood;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent=new Intent(this,SocketService.class);
startService(intent);
fastFood =new FastFood(this);
//this is
xmppConnectio=new XMPPConnectio(this);
}
public void triger()
{
connection=xmppConnectio.getXMPPConnectio();
Intent intent= new Intent(this,chat.class);
startActivity(intent);
}
}
this is the activity which we can access the connection there
package passargad.ehsan;
import android.app.Application;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import java.io.IOException;
public class chat extends ActionBarActivity {
XMPPTCPConnection connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
//this is
connection=MainActivity.connection;
connection.addConnectionListener(new ConnectionListener() {
#Override
public void connected(XMPPConnection connection) {
Log.d("","connected");
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
Log.d("","6");
}
#Override
public void connectionClosed() {
Log.d("","5");
}
#Override
public void connectionClosedOnError(Exception e) {
Log.d("","4");
}
#Override
public void reconnectionSuccessful() {
Log.d("","3");
}
#Override
public void reconnectingIn(int seconds) {
Log.d("","2");
}
#Override
public void reconnectionFailed(Exception e) {
Log.d("","1");
}
});
try {
connection.login();
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related
hi i am building a app where, i show videos from firebase to videoview which is in recyclerview in gridlayout form, means at each fragment there are two videos shown, i want to add on clicklisten to them as when someone click on it, a new activity opens and at that activity, the same video is shown in fullscreen (vertically). i used putextra to transfer my data, but i am getting error, "uristring",
bellow is my code
Adapter code
package com.example.godhelpme.Adapter;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;
import com.example.godhelpme.Fragments.HomeFragment;
import com.example.godhelpme.FullScreen;
import com.example.godhelpme.LoginActivity;
import com.example.godhelpme.MainActivity;
import com.example.godhelpme.Model.Post;
import com.example.godhelpme.Model.User;
import com.example.godhelpme.R;
import com.example.godhelpme.StartActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder>{
private Context mContext;
private List<Post> mPosts;
private FirebaseUser firebaseUser;
public PostAdapter(Context mContext, List<Post> mPosts) {
this.mContext = mContext;
this.mPosts = mPosts;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.upload_item, parent,false);
return new PostAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
Post post = mPosts.get(position);
try {
String link = post.getVideourl();
MediaController mediaController = new MediaController(mContext);
mediaController.setAnchorView(holder.video1);
Uri video = Uri.parse(link);
holder.video1.setMediaController(mediaController);
holder.video1.setVideoURI(video);
holder.video1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
try {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
}
mediaPlayer.setVolume(0f, 0f);
mediaPlayer.setLooping(false);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
mediaController.setVisibility(View.GONE);
}
});
holder.video1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.start(); }
});
holder.id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(view.getContext(),FullScreen.class);
in.putExtra(" videourl", post.getVideourl());
in.putExtra("publisher", post.getPublisher());
in.putExtra("postid", post.getPostid());
view.getContext().startActivity(in);
}
});
}catch (Exception e){
Toast.makeText(mContext,e.getMessage(), Toast.LENGTH_SHORT).show();
}
FirebaseDatabase.getInstance().getReference().child("Users").child(post.getPublisher())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
holder.id.setText(user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return mPosts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public VideoView video1;
public TextView id;
public ViewHolder(#NonNull View itemView) {
super(itemView);
video1 = itemView.findViewById(R.id.video1);
id = itemView.findViewById(R.id.id);
}
}
}
THAT ACTIVITY CODE WHERE I WANT TO SHOW
package com.example.godhelpme;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import com.example.godhelpme.Model.Post;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
public class FullScreen extends AppCompatActivity {
VideoView videoFull;
TextView idFull;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_full_screen);
videoFull = findViewById(R.id.videoFull);
idFull = findViewById(R.id.idFull);
Intent in = getIntent();
try{
String ttr = in.getStringExtra("videourl");
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoFull);
Uri video1 = Uri.parse(ttr);
videoFull.setMediaController(mediaController);
videoFull.setVideoURI(video1);
}catch (Exception e){
Toast.makeText(this,e.getMessage(), Toast.LENGTH_SHORT).show();
}
videoFull.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.start(); }
});
idFull.setText(in.getStringExtra("publisher"));
}
}
PLEASE HELP GUYS PLEASE
It took me three days to figure out what's the problem in my code. After knowing my mistake i am feeling very ashamed as well as happy that i figured, it out.
the mistake is in the adapter code,
in.putExtra(" videourl", post.getVideourl());
String ttr = in.getStringExtra("videourl");
the difference between above two code line is the, in first line there is space before the videourl and in the second line there is no space before videourl, and that's a problem. :-)
When I try to load categories in any activity the quizapp is getting crashed when i load. But when i send users data to firestore, its working.
All the data set in DbQuery.java matches the names entered with Firestore data. But There is something wrong in this that whenever I load this data in login Activity, signup activity or splash activity the app is getting crashed.
Here is my code:
DbQuery.java
package com.nightout.ttsgeneralawareness;
import android.content.Intent;
import android.util.ArrayMap;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.firebase.firestore.WriteBatch;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class DbQuery {
public static FirebaseFirestore g_firestore;
public static List<CategoryModel> g_catList = new ArrayList<>();
public static void createUserData(String email, String name, MyCompleteListener completeListener) {
Map<String, Object> userData = new ArrayMap<>();
userData.put("EMAIL_ID", email);
userData.put("NAME", name);
userData.put("TOTAL_SCORE", 0);
DocumentReference userDoc = g_firestore.collection("USERS")
.document(Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid());
WriteBatch batch = g_firestore.batch();
batch.set(userDoc, userData);
DocumentReference countDoc = g_firestore.collection("USERS").document("TOTAL_USERS");
batch.update(countDoc, "COUNT", FieldValue.increment(1));
batch.commit()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
completeListener.onSuccess();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
completeListener.onFailure();
}
});
}
public static void loadCategories(MyCompleteListener completeListener) {
g_catList.clear();
g_firestore.collection("QUIZ").get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
Map<String, QueryDocumentSnapshot> docList = new ArrayMap<>();
for (QueryDocumentSnapshot doc : queryDocumentSnapshots) {
docList.put(doc.getId(), doc);
}
QueryDocumentSnapshot catListDooc = docList.get("Categories");
long catCount = catListDooc.getLong("COUNT");
for (int i = 1; i <= catCount; i++) {
String catID = catListDooc.getString("CAT" + String.valueOf(i) + "_ID");
QueryDocumentSnapshot catDoc = docList.get(catID);
int noOfTest = catDoc.getLong("NO_OF_TESTS").intValue();
String catName = catDoc.getString("NAME");
g_catList.add(new CategoryModel(catID, catName, noOfTest));
}
completeListener.onSuccess();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
completeListener.onFailure();
}
});
}
LoginActivity.java
package com.nightout.ttsgeneralawareness;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import java.util.Locale;
public class LoginActivity extends AppCompatActivity {
private EditText email, password;
private Button loginButton;
private TextView forgotpwd, signup_button;
private FirebaseAuth mAuth;
private Dialog progressDialog;
private TextView dialogText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
email = findViewById(R.id.email);
password = findViewById(R.id.password);
loginButton = findViewById(R.id.login_button);
forgotpwd = findViewById(R.id.forgot_pwd);
signup_button = findViewById(R.id.signup_button);
//google
progressDialog = new Dialog(LoginActivity.this);
progressDialog.setContentView(R.layout.dialog);
progressDialog.setCancelable(false);
progressDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
dialogText = progressDialog.findViewById(R.id.dialog_text);
dialogText.setText("Signing in...");
mAuth = FirebaseAuth.getInstance();
//google
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (validData())
{
login();
}
}
});
signup_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, SignUpActivity.class);
startActivity(intent);
}
});
}
private boolean validData()
{
if (email.getText().toString().isEmpty())
{
email.setError("Enter E-Mail ID");
return false;
}
if (password.getText().toString().isEmpty())
{
password.setError("Enter Password");
return false;
}
return true;
}
private void login()
{
progressDialog.show();
mAuth.signInWithEmailAndPassword(email.getText().toString().trim(), password.getText().toString().trim())
.addOnCompleteListener(this, task -> {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Toast.makeText(LoginActivity.this,"Login Success",Toast.LENGTH_SHORT).show();
DbQuery.loadCategories(new MyCompleteListener() {
#Override
public void onSuccess() {
progressDialog.dismiss();
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
LoginActivity.this.finish();
}
#Override
public void onFailure() {
progressDialog.dismiss();
Toast.makeText(LoginActivity.this,"Something Went Wrong!",Toast.LENGTH_SHORT).show();
}
});
} else {
progressDialog.dismiss();
// If sign in fails, display a message to the user.
Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
I want to create application which will write text while listening. I have tried this code but this is not working. and i have followed this link. but it couldn't work for me.
If i speak, it is not displaying spoken words and speech recognition is also not working. if you know the solution Please guide me to solve this problem. Thank you...
package com.kp.notesapp;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.fonts.Font;
import android.graphics.pdf.PdfDocument;
import android.graphics.pdf.PdfRenderer;
import android.os.Bundle;
import android.os.Environment;
import android.print.PageRange;
import android.provider.DocumentsContract;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.text.Html;
import android.text.style.ParagraphStyle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.compose.ui.text.Paragraph;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.material.internal.ViewUtils;
import com.kp.notesapp.Models.Notes;
import org.w3c.dom.Document;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
public class NoteView extends AppCompatActivity {
EditText contentEditText;
ImageView micImg;
SpeechRecognizer speechRecognizer;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_view);
getSupportActionBar().hide();
contentEditText = findViewById(R.id.contentNotes);
micImg = findViewById(R.id.micImg);
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
Intent speechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");
speechIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
micImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(count==0){
micImg.setImageResource(R.drawable.micvoice);
speechRecognizer.startListening(speechIntent);
count=1;
}
else{
micImg.setImageResource(R.drawable.mic);
speechRecognizer.stopListening();
count=0;
}
}
});
speechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
/*ArrayList<String> data = bundle.getStringArrayList(speechRecognizer.RESULTS_RECOGNITION);
contentEditText.setText(data.get(0));
Log.e("csData", String.valueOf(data));*/
String str = new String();
Log.e( "csonResults " , String.valueOf(bundle));
ArrayList data = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < data.size(); i++)
{
Log.e("csresult", String.valueOf(data.get(i)));
str += data.get(i);
}
}
#Override
public void onPartialResults(Bundle bundle) {
ArrayList data = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
String word = (String) data.get(data.size() - 1);
contentEditText.setText(word);
Log.e("csWord", word);
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
saveData();
finish();
}
}
While run this code Async fatal error occurs.
I am making an application which will control computer on remote distance like Team viewer.
package pk.edu.cust.fyp.nobeen.sameer.umair.pccontroller;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
Button connectBtn;
EditText ipAddressEditTxt;
String ipAddress;
int port=4444;
boolean connectionResult = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectBtn = (Button) findViewById(R.id.connect);
ipAddressEditTxt = (EditText) findViewById(R.id.ipEditText);
ipAddress = ipAddressEditTxt.getText().toString();
connectBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ClientConnection clientConnection = new ClientConnection();
clientConnection.execute(ipAddress);
if(connectionResult == true) {
Toast.makeText(getApplicationContext(),"Success", Toast.LENGTH_SHORT).show();
Intent intent;
intent = new Intent(MainActivity.this, Login.class);
startActivity(intent);
}
else
Toast.makeText(getApplicationContext(),"Connection Failed",Toast.LENGTH_SHORT).show();
}
});
}
class ClientConnection extends AsyncTask <String,String,String>
{
Socket socket;
DataInputStream dataInputStream;
DataOutputStream dataOutputStream;
Context context;
String TAG ="Client Connection";
#Override
protected String doInBackground(String... params) {
Toast.makeText(getApplicationContext(),"doInBackground run", Toast.LENGTH_SHORT).show();
try {
socket = new Socket(params.toString(), port);
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
Toast.makeText(getApplicationContext(),"Connection is succesfully "+dataInputStream.readUTF(),Toast.LENGTH_SHORT).show();
if(socket.isConnected())
{
connectionResult=true;
}
}catch (Exception ex)
{
Toast.makeText(getApplicationContext(),"Exception occur: "+ex,Toast.LENGTH_SHORT).show();
//Log.e(TAG,ex.toString());
connectionResult = false;
}
return null;
}
protected void onPreExecute()
{
super.onPreExecute();
}
protected void onPostExecute(String s){
Toast.makeText(getApplicationContext(),"OnPost"+connectionResult,Toast.LENGTH_SHORT).show();
//super.onPostExecute(s);
}
}
}
Issue: you are showing Toast in background which not run UI thread. Remove both Toast messages from doInBackground() method
If you wanna show toasts, show them in onPreExecute() and onPostExecute() methods as those are called in UI thread but doInBackground() is being called in separate thread.
I'm trying to use loader with asynctaskloader to load my listview on a fragment but got error with starting the loader:
The method initLoader(int, Bundle, LoaderManager.LoaderCallbacks) in the type LoaderManager is not applicable for the arguments (int, null, context)
I know many have encounterd this error and i did researched but still not solved, can't understand why. If anyone got any ideas please answwer and thanks in advance!
here's my code:
import java.util.ArrayList;
import com.bblackbb.jotdownv2.R;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.content.AsyncTaskLoader;
import android.content.Loader;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.app.Activity;
public class WhiteNote extends Fragment implements **strong text**LoaderManager.LoaderCallbacks<ArrayList<NoteItems>> {
private NoteDatabase note_database;
private int i=0;
public Context context;
public NoteListAdapter noteListAdapter;
public ListView note_listview_container;
public SQLiteDatabase note_sqldb;
public Cursor c;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.white_note, container, false);
context=getActivity();
note_database = new NoteDatabase(context);
final EditText text_ed_1;
final EditText text_ed_2;
Button button_addNote;
Button button_listallNote;
Button button_delallNote;
text_ed_1 = (EditText)rootView.findViewById(R.id.textedit1);
text_ed_2 = (EditText)rootView.findViewById(R.id.textedit2);
button_addNote = (Button)rootView.findViewById(R.id.button1);
button_listallNote = (Button)rootView.findViewById(R.id.button2);
button_delallNote = (Button)rootView.findViewById(R.id.button3);
button_addNote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
note_database.open();
note_database.createData(text_ed_1.getText().toString(),text_ed_2.getText().toString());
//i++;
note_database.close();
}
});
button_listallNote.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
note_database.open();
note_database.get_NoteListAdapter();
note_listview_container.setAdapter(note_database.noteListAdapter);
getLoaderManager().initLoader(0, null,context);
note_database.close();
}
});
button_delallNote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
note_database.open();
note_database.deleteAllNote();
note_database.close();
}
});
return rootView;
}
#Override
public Loader<ArrayList<NoteItems>> onCreateLoader(int id, Bundle args) {
return new NoteItemsLoader(context, note_database);
}
#Override
public void onLoadFinished(Loader<ArrayList<NoteItems>> loader,
ArrayList<NoteItems> data) {
note_listview_container.setAdapter(new NoteListAdapter(context,data));
}
#Override
public void onLoaderReset(Loader<ArrayList<NoteItems>> loader) {
note_listview_container.setAdapter(null);
}
}
class NoteItemsLoader extends AsyncTaskLoader<ArrayList<NoteItems>> {
private ArrayList<NoteItems> loader_note_items= new ArrayList<NoteItems>();
private NoteDatabase loader_db;
public NoteItemsLoader(Context context, NoteDatabase db) {
super(context);
loader_db = db;
}
#Override
protected void onStartLoading() {
if (loader_note_items != null) {
deliverResult(loader_note_items); // Use the cache
}
else
forceLoad();
}
#Override
protected void onStopLoading() {
cancelLoad();
}
#Override
public ArrayList<NoteItems> loadInBackground() {
loader_db.open(); // Query the database
ArrayList<NoteItems> note_items = new ArrayList<NoteItems>();
loader_db.get_NoteListLoader(note_items,loader_db);
loader_db.close();
return note_items;
}
#Override
public void deliverResult(ArrayList<NoteItems> data) {
loader_note_items = data; // Caching
super.deliverResult(data);
}
#Override
protected void onReset() {
super.onReset();
onStopLoading();
loader_note_items = null;
}
#Override
public void onCanceled(ArrayList<NoteItems> data) {
super.onCanceled(data);
loader_note_items = null;
}
protected void onReleaseResources(ArrayList<NoteItems> data) {}
}
replace
getLoaderManager().initLoader(0, null,context);
with
getLoaderManager().initLoader(0, null,WhiteNote.this);
here your WhiteNode class implements LoaderManager.LoaderCallbacks but your Activity class in not implementing. so you have to pass reference of WhiteNote class.
and once check imports section as #Praveen Sharma said
Try to replace your old imports with these
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
hope this will fix your problem.