How to stop receiving data from a web server? - java

I have an Activity that receives and displays information from the web server and saves it to the database and, if it has already received the information once, it will read from the database.
There is no problem running the program, only when the user enters the activity and still does not receive the information from the server, exit the activity, in another Activity the application crashes.
This problem is to quit the activity because when staying in activity and loaded data completely, we have not any problems. also when reading data from the database we have not any problems.
How can stop receive data when the user quit the activity or solve this problem form another way.
This is my activity codes:
public class ShowProduct extends AppCompatActivity {
private RequestQueue mQueue;
private String id;
private Products products;
private DatabaseHelper databaseHelper;
private ProgressBar progressBar;
private Typeface IranSans,IranSansBold;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_product);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
databaseHelper = new DatabaseHelper(this);
products = new Products();
progressBar = (ProgressBar)findViewById(R.id.progressBar);
IranSans = Typeface.createFromAsset(getAssets(),"fonts/IRANSansWeb.ttf");
IranSansBold = Typeface.createFromAsset(getAssets(),"fonts/IRANSansWeb_Bold.ttf");
Bundle extras = getIntent().getExtras();
id= extras.getString("id");
try {
if (databaseHelper.dbContentChecker(id)) {
if (connectionCheck() == false){
Intent intent = new Intent(this, NoInternetConnection.class);
startActivity(intent);
}
String url = "https://website.com/webserver/?id=" + id;
mQueue = Volley.newRequestQueue(this);
jsonParse(url);
} else {
products = databaseHelper.getOneProduct(id);
showFromDB(products);
}
}catch (Exception ex){
}
//footer set
Footer footer = new Footer();
footer.footerSet(ShowProduct.this, this);
}
private void showFromDB(Products products) {
TextView tx = (TextView)findViewById(R.id.title);
tx.setTypeface(IranSansBold);
tx.setText(products.getName());
ImageView im = (ImageView)findViewById(R.id.image);
Glide.with(ShowProduct.this)
.asBitmap()
.load(products.getImage())
.into(im);
TextView tc = (TextView)findViewById(R.id.content);
tc.setTypeface(IranSans);
tc.setText(Html.fromHtml(products.getContent()));
progressBar.setVisibility(View.GONE);
}
private void jsonParse(String url) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("send");
JSONObject send = jsonArray.getJSONObject(0);
String title = send.getString("title");
String image = send.getString("image");
String content = send.getString("content");
TextView tx = (TextView)findViewById(R.id.title);
tx.setTypeface(IranSansBold);
tx.setText(title);
ImageView im = (ImageView)findViewById(R.id.image);
Glide.with(ShowProduct.this)
.asBitmap()
.load(image)
.into(im);
TextView tc = (TextView)findViewById(R.id.content);
tc.setTypeface(IranSans);
tc.setText(Html.fromHtml(content));
//Save in Database
try {
products.setProductId(id);
products.setName(title);
products.setImage(image);
products.setContent(content);
databaseHelper.editProduct(products);
}catch (Exception ex){
Toast.makeText(ShowProduct.this, "Error DB", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
//Toast.makeText(getApplicationContext(), ""+Temp , Toast.LENGTH_SHORT).show();
}
public boolean connectionCheck() {
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
return true;
}
else
return false;
}
}

First of all you should think about your architecture. Handling fetching data inside an Activity is not a good practice. Look at MVVM or MVP and try to put your data fetching logic in another layer.
For your specific problem you should try to cancle the request in the onStop() method of the Activity, see:
https://developer.android.com/training/volley/simple#cancel

Related

android studio getting data from php database and populating the activity

i'm trying to get the data from the database to fill the activity with them but i'm not getting anything this is the db code i have 2 Textvies 1 image view i'm trying to fill with the data i'm new to mobile programming so need help:
public void gettypedet(final int tid, final TextView ttitle, final ImageView timg, final TextView desc) {
String url = "http://192.168.0.114/mobileshop/product_typrbyid.php?id="+tid;
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(context);
// Request a json response from the provided URL.
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject prt) {
try {
String type=prt.getString("type");
int imgname=Integer.parseInt(prt.getString("imagename"));
String des=prt.getString("description");
ttitle.setText(type);
timg.setImageResource(imgname);
desc.setText(des);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("error", error.toString());
}
});
// Add the request to the RequestQueue.
queue.add(jsonRequest);
}
this is my php code i tested it and it's working so shouldn't be the problem:
<?php
require_once("connection.php");
$id=$_GET["id"];
$q="Select * from product_type where id='$id'";
$res=mysqli_query($con,$q);
while($row=mysqli_fetch_assoc($res)){
$types[]=$row;
}
echo (json_encode($types));
mysqli_free_result($res);
?>
this is the activity code here not sure if i did something wrong:
public class ptype_detail extends Activity {
int kposition,tposition,id;
TextView ttitle,tdes;
ImageView timg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ptype_detail);
tposition=(Integer)getIntent().getExtras().get("tpos");
kposition=(Integer)getIntent().getExtras().get("kpos");
if (kposition==0)
id=tposition+5;
else if(kposition==1)
id=tposition+18;
else if (kposition==2)
id=tposition+20;
else
id=tposition;
ttitle=(TextView)findViewById(R.id.title) ;
tdes=(TextView)findViewById(R.id.typedes);
timg=(ImageView)findViewById(R.id.titleimage);
shop db=new shop(this);
db.gettypedet(id,ttitle,timg,tdes);
}
}

How to save fragment onButtonClick and load on next program start

I have an app where I have a fragment.Let's call it mainScreen. In mainScreen there's a button and onClick() opens second fragment. Let's call it FragmentHomePage. In FragmentHomePage i have a retrofit. There's a button named logOut. My problem is, when user not clicked logOut, i want to save this fragment and load this fragment. In default when app starts, opens mainScreen, but if user not clicks logOut, i need open FragmentHomePage on app start. How can i do this?
public class FragmentHomePage extends BaseFragment {
View mainView;
TextView fullName, userName, email;
Button logOut;
ApiClient apiClient = ApiClient.getInstance();
SupportObjToken supportopToken = new SupportObjToken();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.home_page, container, false);
init(mainView);
newTokenCall();
return mainView;
}
private void init(View v) {
fullName = v.findViewById(R.id.fullName);
userName = v.findViewById(R.id.user);
email = v.findViewById(R.id.mail);
logOut = v.findViewById(R.id.logOut);
}
public void newTokenCall() {
String clientID = SharedPreferencesManager.getInstance().getClientID();
String clientSecret = SharedPreferencesManager.getInstance().getClientSecret();
String refreshToken = SharedPreferencesManager.getInstance().getRefreshToken();
String newRefreshToken = SharedPreferencesManager.getInstance().getNewRefreshToken();
final String firstName = SharedPreferencesManager.getInstance().getFirstName();
final String lastName = SharedPreferencesManager.getInstance().getLastName();
final String mail = SharedPreferencesManager.getInstance().getEmail();
final String user = SharedPreferencesManager.getInstance().getUsername();
supportopToken.setGrantType("refresh_token");
supportopToken.setClientId(clientID);
supportopToken.setClientSecret(clientSecret);
supportopToken.setRefreshToken(refreshToken);
Call<ResponseBody> newToken = apiClient.newToken(supportopToken);
newToken.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String newDataAccess = response.body().string();
JSONObject obj = new JSONObject(newDataAccess);
String newAccessToken = obj.getString("accessToken");
String newRefreshToken = obj.getString("refreshToken");
SharedPreferencesManager.getInstance().setNewAccessToken(newAccessToken);
SharedPreferencesManager.getInstance().setNewRefreshToken(newRefreshToken);
fullName.setText(firstName + " " + lastName);
userName.setText(user);
email.setText(mail);
} catch (IOException | JSONException e) {
e.printStackTrace();
}
} else if (response.code() == 401) {
supportopToken.setRefreshToken(SharedPreferencesManager.getInstance().getNewRefreshToken());
Call<ResponseBody> newToken1 = apiClient.newToken(supportopToken);
newToken1.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String newDataAccess = response.body().string();
JSONObject obj = new JSONObject(newDataAccess);
String newAccessToken = obj.getString("accessToken");
String newRefreshToken = obj.getString("refreshToken");
SharedPreferencesManager.getInstance().setNewAccessToken(newAccessToken);
SharedPreferencesManager.getInstance().setNewRefreshToken(newRefreshToken);
fullName.setText(firstName + " " + lastName);
userName.setText(user);
email.setText(mail);
} catch (JSONException | IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getActivity(), "You're on failure getting new Token", Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getActivity(), "You're on failure getting new Token", Toast.LENGTH_SHORT).show();
}
});
}}
How can i do this part? Thanks. Yeah and not give negative vote. I'm a beginner on this site)).
Here's the activity where i'm launching the fragments.
public class MainActivity extends AppCompatActivity implements FragmentChangeListener {
FragmentActivity fragmentActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ApiClient.initializeInstance("simple web page");
fragmentActivity = new FragmentActivity();
this.replaceFragment(fragmentActivity, true);
SharedPreferencesManager.init(this);
}
#Override
public void replaceFragment(BaseFragment fragment, Boolean isAddToBackStack) {
String backStateName = fragment.getClass().getName();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container, fragment, fragment.toString());
transaction.addToBackStack(backStateName);
transaction.commit();
}}
In your mainScreen button onclick, add a key to shared preferences like this
SharedPreferences.Editor editor = getSharedPreferences("APP_PREF", MODE_PRIVATE).edit();
editor.putString("state", "logged_in");
editor.apply();
inside your logOut button onclick in FragmentHomePage add the following code
SharedPreferences.Editor editor = getSharedPreferences("APP_PREF", MODE_PRIVATE).edit();
editor.putString("state", "logged_out");
editor.apply();
Now inside your first fragment's oncreate add this
SharedPreferences prefs = getSharedPreferences("APP_PREF", MODE_PRIVATE);
String state = prefs.getString("state", "state");
if(state.equals("logged_in"){
//load second fragment here
}
save a boolean value in SharedPreferences with default value false.
PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).edit().putBoolean("ISUSERALREADYLOGGEDIN", false).apply();
when ever you come to the FragmentHomePage , set this value to true.
PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).edit().putBoolean("ISUSERALREADYLOGGEDIN", true).apply();
When user clicks logout button , set this value to false again.
PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).edit().putBoolean("ISUSERALREADYLOGGEDIN", false).apply();
From the Base Activity which is keeping these fragments,
When you launch the mainScreen fragment, check this value, with this code :
PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).getBoolean("ISUSERALREADYLOGGEDIN", false);
If the value is true, launch the HomeFragment, else launch the mainScreen fragment.
Use this function to launch the fragment:
public void launchFragmentByReplacing(Fragment fragment, String incomingFragmentTag) {
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(frameLayout.getId(), fragment, incomingFragmentTag);
transaction.commit();
manager.executePendingTransactions();
}
In your case, right before :
this.replaceFragment(fragmentActivity, true);
check for the SharedPref value.
Boolean isloggedIn = PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).getBoolean("ISUSERALREADYLOGGEDIN", false);
if(isloggedIn) //is true
this.replaceFragment(new FragmentActivity(), true);
else
this.replaceFragment(new FragmentHomePage(), true);

Retrieve data from database to my app (NOT WORKING)

so i am trying to retrieve data stored in my database.
basically the user inputs a car registration number and a rating (between 1-5)and click button. once the button is clicked my code will execute. which gets text from both editext and send to my server. i have php file saved, which will check if the carregistration number matches the value in the databse. if it matches retrieve the current rating stored in the database. the value is then showed on another acitivity. The php file works fine. i tried by inserting value manually. the problem i have is that when the button is clicked nothign happens. i have used this code to retrieve user name and other details on another app.
dataretrieve.java
public class DataRetrieve extends StringRequest {
private static final String REGISTER_REQUEST_URL = "https://dipteran-thin.000webhostapp.com/Login1.php";
private Map<String, String> params;
public DataRetrieve (String carreg, int rating, Response.Listener<String> listener) {
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("carreg", carreg);
params.put("rating", rating + "");
}
#Override
public Map<String, String> getParams() {
return params;
}
}
Profile.java (where the user inputs carreg and rating)
public class Profile extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
final EditText editText = (EditText) findViewById(R.id.carreg);
final EditText editText1 = (EditText) findViewById(R.id.editText3);
Button button = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String carreg = editText.getText().toString();
final int rating = Integer.parseInt(editText1.getText().toString());
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
int rating = jsonResponse.getInt("rating");
Intent intent = new Intent(Profile.this, UserAreaActivity.class);
intent.putExtra("rating", rating);
Profile.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
DataRetrieve loginRequest = new DataRetrieve(carreg, rating, responseListener);
RequestQueue queue = Volley.newRequestQueue(Profile.this);
queue.add(loginRequest);
}});
}
}
userareaactivity.java (where value is shown when retrieved)
public class UserAreaActivity extends AppCompatActivity {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
final TextView etusername = (TextView) findViewById(R.id.textView2);
final TextView etwelcome = (TextView) findViewById(R.id.textView);
final TextView etuname = (TextView) findViewById(R.id.textView3);
final Button Logout = (Button) findViewById(R.id.logout);
//String Name = SharedPreferenceUtils.getName(this);
//etwelcome.setText(Name);
Intent intent = getIntent();
username = intent.getIntExtra("rating", -1);
etusername.setText(username + "");
//Intent in = new Intent(getApplicationContext(), Messages.class);
//in.putExtra("username", username);
//UserAreaActivity.this.startActivity(in);
}
#Override
public void onBackPressed(){
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
Intent intent = new Intent(UserAreaActivity.this, Messages.class);
UserAreaActivity.this.startActivity(intent);
}
return true;
}
I'm getting an error from your php page:
<b>Parse error</b>: syntax error, unexpected ']' in <b>/storage/ssd1/526/2972526/public_html/Login1.php</b> on line <b>8</b><br />
You can see the output of your response in the log by using this line above your JSON parsing (before it throws the exception)
Log.d("Response", response.toString());
I copied your success block into the exception block and it works as expected, so that code is valid. I would also put some kind of alert in the catch to let you know the failure happened when you're done testing.
Side note, change your parameter line to this...it's cleaner:
params.put("rating", String.valueOf(rating));

Android- Image not getting loaded

When I click on an image in our project, another image gets loaded. It works fine, but when I go back to the previous activity, and click on the same image, it doesn't get loaded.
This is the first activity which opens when app is active. This page will show grid of pictures
public class GentsActivity extends Fragment implements AdapterView.OnItemClickListener {
//Web api url
public static final String DATA_URL = "PHP LINK HERE";
//Tag values to read from json
public static final String TAG_IMAGE_URL = "small_image_url";
//GridView Object
private GridView gridView;
//ArrayList for Storing image urls and titles
private ArrayList<String> images;
private SwipeRefreshLayout swipeContainer;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Returning the layout file after inflating
//Change R.layout.tab1 in you classes
View view= inflater.inflate(R.layout.activity_gents, container, false);
gridView = (GridView) view.findViewById(R.id.gridView);
getData();
//swipeContainer = (SwipeRefreshLayout) view.findViewById(R.id.swipeContainer);
images = new ArrayList<>();
//Calling the getData method
/*swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// Your code to refresh the list here.
// Make sure you call swipeContainer.setRefreshing(false)
// once the network request has completed successfully.
//Toast.makeText(this,"refresh ",Toast.LENGTH_SHORT).show();
Intent mIntent= new Intent(SareeActivity.this,SareeActivity.class);
startActivity(mIntent);
swipeContainer.setRefreshing(false);
}
});*/
return view;
}
private void getData(){
//Showing a progress dialog while our app fetches the data from url
//final ProgressDialog loading = ProgressDialog.show(this, "Please wait,","Fetching data.",false,false);
//Creating a json array request to get the json from our api
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing the progressdialog on response
// loading.dismiss();
//Displaying our grid
showGrid(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
//Adding our request to the queue
requestQueue.add(jsonArrayRequest);
}
private void showGrid(JSONArray jsonArray){
//Looping through all the elements of json array
for(int i = 0; i<jsonArray.length(); i++){
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = jsonArray.getJSONObject(i);
// Log.d(TAG_IMAGE_URL,"JSON SHOW GRID"+obj);
//getting image url and title from json object
images.add(obj.getString(TAG_IMAGE_URL));
Log.d(TAG_IMAGE_URL,"JSON SHOW GRID"+images);
} catch (JSONException e) {
e.printStackTrace();
}
}
//Creating GridViewAdapter Object
//Adding adapter to gridview
GridViewAdapter gridViewAdapter = new GridViewAdapter(getContext(),images);
gridView.setAdapter(gridViewAdapter);
gridView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String prompt = (String)adapterView.getItemAtPosition(i);
Intent mIntent= new Intent(getActivity(),LoadPhotoGents.class);
mIntent.putExtra("s",prompt);
startActivity(mIntent);
}
}
When I click on a particular photo, that single photo will open. The code is given below
public class LoadPhotoGents extends AppCompatActivity {
private String data, path;
private ImageView ivi;
public static final String DATA_URL = "PHP LINK HERE";
private static int id=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load_photo_gents);
data = getIntent().getExtras().getString("s");
path = data.replace(".JPG", "big.JPG");
//Toast.makeText(this, "Path:" + path, Toast.LENGTH_LONG).show();
ivi = (ImageView) findViewById(R.id.fullImage);
Picasso.with(LoadPhotoGents.this).load(path).into(ivi);
getData();
ImageViewTouch img = (ImageViewTouch) findViewById(R.id.fullImage);
img.setBackgroundColor(Color.parseColor("#000000"));
ivi.buildDrawingCache();
Bitmap bmap=ivi.getDrawingCache();
//img.setFitToScreen(true);
img.setImageBitmap(bmap);
}
private void getData(){
String url=DATA_URL+data.trim();
StringRequest stringRequest=new StringRequest(url,new Response.Listener<String>(){
#Override
public void onResponse(String response){
showJSON(response);
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
}
});
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String name= "";
try{
JSONArray jsonArray=new JSONArray(response);
//JSONArray result= jsonObject.getJSONArray("result");
JSONObject datas=jsonArray.getJSONObject(0);
name=datas.getString("description");
}catch(JSONException e){
Toast.makeText(this,"inside getData: "+name,Toast.LENGTH_SHORT).show();
}
}
}
This will definitely help you to debug the issue. In your code I can see that you are loading the image directly using Picasso.with().load().into() problem with this method is you do not know what is happening at the background.
You can do two things. First use Callback when you load the image into the ImageView as below
Picasso.with(LoadPhotoGents.this).load(path).into(ivi, new Callback()
{
#Override
public void onSuccess()
{
Timber.d("Image Loaded Successfully");
}
#Override
public void onError()
{
Timber.d("Error Loading Image");
}
});
Above can be used to handle image loaded/not loaded scenario.
Now coming to the actual error while loading the image, you need to use a Picasso.Builder which has a listener which will help you know the actual error.
Build Picasso Builder as below
Picasso.Builder builder = new Picasso.Builder(mContext);
builder.listener(new Picasso.Listener()
{
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception)
{
Timber.d(exception.getMessage());
}
});
Picasso pic = builder.build();
To Load the image do the following
pic.load(path).into(ivi, new Callback()
{
#Override
public void onSuccess()
{
Timber.d("Image Loaded Successfully");
}
#Override
public void onError()
{
Timber.d("Image Load Error");
}
});
Ensure that path variable is not null or empty

Video and audio call 2 Android devices - webrtc

I'm trying do develop Android app which will send audio and video via webrtc protocol between devices. This code works well with Android and web interface, but not between two Androids. Every time connection is opened and popup says that devices are connected, but there is no sound and picture. I tried a lot of things, but nothing helped. Dependencies and permissions are ok. Used my own pub and sub keys from PubNub. It opens connection 1 of 20 times between two Androids, so I think that something isn't working well here.
Followed this tutorial to create app: tutorial
I found this error image
Camera is crashing somewhere, but I really don't know why.
public static final String VIDEO_TRACK_ID = "videoPN";
public static final String AUDIO_TRACK_ID = "audioPN";
public static final String LOCAL_MEDIA_STREAM_ID = "localStreamPN";
private PnRTCClient pnRTCClient;
private VideoSource localVideoSource;
private VideoRenderer.Callbacks localRender;
private VideoRenderer.Callbacks remoteRender;
private GLSurfaceView mVideoView;
private String username;
private class MyRTCListener extends PnRTCListener {
#Override
public void onLocalStream(final MediaStream localStream) {
VideoChatActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if(localStream.videoTracks.size()==0) return;
localStream.videoTracks.get(0).addRenderer(new VideoRenderer(localRender));
}
});
}
#Override
public void onAddRemoteStream(final MediaStream remoteStream, final PnPeer peer) {
VideoChatActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(VideoChatActivity.this,"Connected to " + peer.getId(), Toast.LENGTH_SHORT).show();
try {
if(remoteStream.videoTracks.size()==0) return;
remoteStream.videoTracks.get(0).addRenderer(new VideoRenderer(remoteRender));
VideoRendererGui.update(remoteRender, 0, 0, 100, 100, VideoRendererGui.ScalingType.SCALE_ASPECT_FILL, false);
VideoRendererGui.update(localRender, 72, 72, 25, 25, VideoRendererGui.ScalingType.SCALE_ASPECT_FIT, true);
}
catch (Exception e){ e.printStackTrace(); }
}
});
}
#Override
public void onPeerConnectionClosed(PnPeer peer) {
Intent intent = new Intent(VideoChatActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videochatactivity);
Bundle extras = getIntent().getExtras();
if (extras == null || !extras.containsKey(Constants.USER_NAME)) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
Toast.makeText(this, "Need to pass username to VideoChatActivity in intent extras (Constants.USER_NAME).",
Toast.LENGTH_SHORT).show();
finish();
return;
}
this.username = extras.getString(Constants.USER_NAME, "");
PeerConnectionFactory.initializeAndroidGlobals(
this, // Context
true, // Audio Enabled
true, // Video Enabled
true, // Hardware Acceleration Enabled
null); // Render EGL Context
PeerConnectionFactory pcFactory = new PeerConnectionFactory();
this.pnRTCClient = new PnRTCClient(Constants.PUB_KEY, Constants.SUB_KEY, this.username);
int camNumber = VideoCapturerAndroid.getDeviceCount();
String frontFacingCam = VideoCapturerAndroid.getNameOfFrontFacingDevice();
String backFacingCam = VideoCapturerAndroid.getNameOfBackFacingDevice();
VideoCapturerAndroid capturer = (VideoCapturerAndroid) VideoCapturerAndroid.create(frontFacingCam);
localVideoSource = pcFactory.createVideoSource(capturer, this.pnRTCClient.videoConstraints());
VideoTrack localVideoTrack = pcFactory.createVideoTrack(VIDEO_TRACK_ID, localVideoSource);
AudioSource audioSource = pcFactory.createAudioSource(this.pnRTCClient.audioConstraints());
AudioTrack localAudioTrack = pcFactory.createAudioTrack(AUDIO_TRACK_ID, audioSource);
MediaStream mediaStream = pcFactory.createLocalMediaStream(LOCAL_MEDIA_STREAM_ID);
mediaStream.addTrack(localVideoTrack);
mediaStream.addTrack(localAudioTrack);
this.mVideoView = (GLSurfaceView) findViewById(R.id.gl_surface);
VideoRendererGui.setView(mVideoView, null);
remoteRender = VideoRendererGui.create(0, 0, 100, 100, VideoRendererGui.ScalingType.SCALE_ASPECT_FILL, false);
localRender = VideoRendererGui.create(0, 0, 100, 100, VideoRendererGui.ScalingType.SCALE_ASPECT_FILL, true);
this.pnRTCClient.attachRTCListener(new MyRTCListener());
this.pnRTCClient.attachLocalMediaStream(mediaStream);
this.pnRTCClient.listenOn(this.username);
this.pnRTCClient.setMaxConnections(1);
if (extras.containsKey(Constants.JSON_CALL_USER)) {
String callUser = extras.getString(Constants.JSON_CALL_USER, "");
connectToUser(callUser);
}
}
public void connectToUser(String user) {
this.pnRTCClient.connect(user);
}
public void hangup(View view) {
this.pnRTCClient.closeAllConnections();
startActivity(new Intent(VideoChatActivity.this, MainActivity.class));
}
#Override
protected void onDestroy() {
super.onDestroy();
if (this.localVideoSource != null) {
localVideoSource.stop();
}
if (this.pnRTCClient != null) {
this.pnRTCClient.onDestroy();
this.pnRTCClient.closeAllConnections();
}
}
Here is MainActivity if it will help:
private SharedPreferences mSharedPreferences;
private TextView mUsernameTV;
private EditText mCallNumET;
// private Pubnub mPubNub;
private String username;
private Pubnub mPubNub;
public void initPubNub() {
String stdbyChannel = this.username + Constants.STDBY_SUFFIX;
this.mPubNub = new Pubnub(Constants.PUB_KEY, Constants.SUB_KEY);
this.mPubNub.setUUID(this.username);
try {
this.mPubNub.subscribe(stdbyChannel, new Callback() {
#Override
public void successCallback(String channel, Object message) {
Log.d("MA-success", "MESSAGE: " + message.toString());
if (!(message instanceof JSONObject)) return; // Ignore if not JSONObject
JSONObject jsonMsg = (JSONObject) message;
try {
if (!jsonMsg.has(Constants.JSON_CALL_USER)) return;
String user = jsonMsg.getString(Constants.JSON_CALL_USER);
// Consider Accept/Reject call here
Intent intent = new Intent(MainActivity.this, VideoChatActivity.class);
intent.putExtra(Constants.USER_NAME, username);
intent.putExtra(Constants.JSON_CALL_USER, user);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} catch (PubnubException e) {
e.printStackTrace();
}
}
public void makeCall(View view){
String callNum = mCallNumET.getText().toString();
if (callNum.isEmpty() || callNum.equals(this.username)) {
Toast.makeText(this, "Enter a valid number.", Toast.LENGTH_SHORT).show();
}
dispatchCall(callNum);
}
public void dispatchCall(final String callNum) {
final String callNumStdBy = callNum + Constants.STDBY_SUFFIX;
JSONObject jsonCall = new JSONObject();
try {
jsonCall.put(Constants.JSON_CALL_USER, this.username);
mPubNub.publish(callNumStdBy, jsonCall, new Callback() {
#Override
public void successCallback(String channel, Object message) {
Log.d("MA-dCall", "SUCCESS: " + message.toString());
Intent intent = new Intent(MainActivity.this, VideoChatActivity.class);
intent.putExtra(Constants.USER_NAME, username);
intent.putExtra(Constants.JSON_CALL_USER, callNum);
startActivity(intent);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.mSharedPreferences = getSharedPreferences(Constants.SHARED_PREFS, MODE_PRIVATE);
// Return to Log In screen if no user is logged in.
if (!this.mSharedPreferences.contains(Constants.USER_NAME)){
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
return;
}
this.username = this.mSharedPreferences.getString(Constants.USER_NAME, "");
this.mCallNumET = (EditText) findViewById(R.id.call_num);
this.mUsernameTV = (TextView) findViewById(R.id.main_username);
this.mUsernameTV.setText(this.username); // Set the username to the username text view
//TODO: Create and instance of Pubnub and subscribe to standby channel
// In pubnub subscribe callback, send user to your VideoActivity
initPubNub();
}
I will appreciate any help. Thanks to everybody.
when You run your application that time they ask sign in usename
that time you wrote your name
put that name in VideoChatActivity class
this.pnRTCClient.listenOn("your name when your wrote at signin time");
this.pnRTCClient.setMaxConnections(3);

Categories

Resources