Null point Exception while sending message - quickblox

I have added new class file under /com.quickblox.q_municate/ui/friends. I want to send message to another user. I have written code using Quickblox API, code is as follows.
public class ChangeDSConfiguration extends Activity{
TextView OpenSwitchRelayFor;
TextView OpenPowerRelayFor;
TextView PowerRelayCode;
TextView SwitchRelayCode;
TextView SecretPassword;
EditText OpenSwitchRelayForValue;
EditText OpenPowerRelayForValue;
EditText PowerRelayCodeValue;
EditText SwitchRelayCodeValue;
EditText SecretPasswordValue;
Button ChangeConfiguration;
String password;
String configurationDetails;
int id;
public static void start(Context context, int id) {
Intent intent = new Intent(context, ChangeDSConfiguration.class);
intent.putExtra(QBServiceConsts.USER_ID, id);
context.startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_dsconfiguration);
id = getIntent().getExtras().getInt(QBServiceConsts.USER_ID);
Log.e("ChangeConfig", "id = "+id);
OpenSwitchRelayFor = (TextView) findViewById(R.id.openSwitchRelayFor);
OpenPowerRelayFor = (TextView) findViewById(R.id.openPowerRelayFor);
PowerRelayCode = (TextView) findViewById(R.id.powerRelayCode);
SwitchRelayCode = (TextView) findViewById(R.id.switchRelayCode);
SecretPassword = (TextView) findViewById(R.id.secretPassword);
OpenSwitchRelayForValue = (EditText) findViewById(R.id.etOpenSwitchRelayFor);
OpenPowerRelayForValue = (EditText) findViewById(R.id.etOpenPowerRelayFor);
PowerRelayCodeValue = (EditText) findViewById(R.id.etPowerRelayCode);
SwitchRelayCodeValue = (EditText) findViewById(R.id.etSwitchRelayCode);
SecretPasswordValue = (EditText) findViewById(R.id.etSecretPassword);
ChangeConfiguration = (Button) findViewById(R.id.changeConfiguration);
ChangeConfiguration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showAskForSecretPasswordDialog();
}
});
}
public void showAskForSecretPasswordDialog(){
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.layout_enter_password, null);
final EditText secret_password;
secret_password = (EditText) view.findViewById(R.id.secretPassword);
secret_password.setText("");
secret_password.setFocusable(true);
AlertDialog.Builder askForPasswordDialog = new AlertDialog.Builder(ChangeDSConfiguration.this);
askForPasswordDialog.setView(view);
askForPasswordDialog.setCancelable(false);
askForPasswordDialog.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
password = secret_password.getText().toString();
Log.e("FriendsListFragment", "password = " + password);
if(password.equals("")){
Toast.makeText(ChangeDSConfiguration.this, "Please enter password before you continue", Toast.LENGTH_LONG).show();
return;
}else{
password = "Change Configuration:" + password; // frame relay code message, with header and relay type
sendConfigurartionDetails(password);
finish();
}
}
});
askForPasswordDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
return ;
}
});
askForPasswordDialog.setTitle(R.string.title_enter_relay_code);
askForPasswordDialog.setMessage(R.string.message_enter_relay_code);
askForPasswordDialog.show();
return;
}
public void sendConfigurartionDetails(String password){
if (!QBChatService.isInitialized()) {
Log.e("ChangeConfig", "(!QBChatService.isInitialized())");
QBChatService.init(this);
}
configurationDetails = password + ":" + getConfigurationDetails();
Log.e("ChangeDSConfig", "configurationDetails = "+configurationDetails);
try {
QBChatMessage message = new QBChatMessage();
message.setBody(configurationDetails);
QBPrivateChatManager privateChatManager = QBChatService.getInstance().getPrivateChatManager();
Log.e(" ChangeDSConfig", "id = "+id);
QBPrivateChat privateChat = privateChatManager.getChat(id);
Log.e(" ChangeDSConfig", "getChat(id);");
if (privateChat == null) {
privateChat = privateChatManager.createChat(id, null);
Log.e(" ChangeDSConfig", "Private chat created");
}
privateChat.sendMessage(message);
Log.e(" ChangeDSConfig", "Power Relay Code sent");
} catch (XMPPException e) {
Toast.makeText(ChangeDSConfiguration.this,e.getMessage(), Toast.LENGTH_LONG).show();
} catch (SmackException.NotConnectedException e) {
Toast.makeText(ChangeDSConfiguration.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
}
public String getConfigurationDetails(){
String str1 = OpenSwitchRelayForValue.getText().toString();
String str2 = OpenPowerRelayForValue.getText().toString();
String str3 = PowerRelayCodeValue.getText().toString();
String str4 = SwitchRelayCodeValue.getText().toString();
String str5 = SecretPasswordValue.getText().toString();
String str6 = str1 + ":" + str2 + ":" + str3 + ":" + str4 + ":" + str5 ;
return str6;
}
}
I am getting Null point exception here
QBPrivateChat privateChat = privateChatManager.getChat(id);

Apparently the previous call returns null:
QBChatService.getInstance().getPrivateChatManager();
Check your getPrivateChatManager() implementation.

Related

Implement Infinite scroll with ViewModel And Retrofit in recyclerview

Before adding viewmodel & livedata , i successfully implemented infinity scroll with retrofit. But after adding viewmodel & livedata with Retrofit, My can't update recyclerview with new data call or viewmodel observer not update the list.
I simply want to infinite scrolling as my code does before. I add a global variable to reuse next page token. Am i missing anything or any sample to implement infinite recyclerview with viewmodel & retrofit will be awesome.
public static String NEXT_PAGE_URL = null;
I coded like that.
My Activity -> PlaceListActivity
placeRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
LogMe.d(tag, "onScrollStateChanged:: " + "called");
// check scrolling started or not
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
isScrolling = true;
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
LogMe.d(tag, "onScrolled:: " + "called");
super.onScrolled(recyclerView, dx, dy);
currentItem = layoutManager.getChildCount();
totalItems = layoutManager.getItemCount();
scrolledOutItems = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
LogMe.d(tag, "currentItem:: " + currentItem);
LogMe.d(tag, "totalItems:: " + totalItems);
LogMe.d(tag, "scrolledOutItems:: " + scrolledOutItems);
if (isScrolling && (currentItem + scrolledOutItems == totalItems)) {
LogMe.d(tag, "view:: " + "finished");
isScrolling = false;
if (ApplicationData.NEXT_PAGE_URL != null) {
LogMe.d(tag, "place adding:: " + " onScrolled called");
ll_loading_more.setVisibility(View.VISIBLE);
// todo: call web api here
callDataFromLocationAPi(type, ApplicationData.NEXT_PAGE_URL, currentLatLng);
} else {
LogMe.d(tag, "next_page_url:: " + " is null");
}
}
}
});
private void callDataFromLocationAPi(String type, String next_page_url, LatLng latLng) {
if (Connectivity.isConnected(activity)) {
showProgressDialog();
model.getNearestPlaces(type, next_page_url, latLng).
observe(activity, new Observer<List<PlaceDetails>>() {
#Override
public void onChanged(#Nullable List<PlaceDetails> placeDetails) {
ll_loading_more.setVisibility(View.GONE);
LogMe.i(tag, "callDataFromLocationAPi: onChanged called !");
hideProgressDialog();
if (placeDetails != null) {
placeDetailsList = placeDetails;
placeListAdapter.setPlaceList(placeDetails);
}
}
});
} else {
showAlertForInternet(activity);
}
}
In PlaceViewModel
public class PlaceViewModel extends AndroidViewModel {
//this is the data that we will fetch asynchronously
private MutableLiveData<List<PlaceDetails>> placeList;
private PlaceRepository placeRepository;
private String tag = getClass().getName();
public PlaceViewModel(Application application) {
super(application);
placeRepository = new PlaceRepository(application);
}
//we will call this method to get the data
public MutableLiveData<List<PlaceDetails>> getNearestPlaces(String type,
String next_page_token,
LatLng latLng) {
//if the list is null
if (placeList == null) {
placeList = new MutableLiveData<>();
//we will load it asynchronously from server in this method
//loadPlaces(type, next_page_token, latLng);
placeList = placeRepository.getNearestPlacesFromAPI(type, next_page_token, latLng);
}
//finally we will return the list
return placeList;
}
}
In my PlaceRepository.java looks
public class PlaceRepository {
private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
#Override
public void migrate(SupportSQLiteDatabase database) {
// Since we didn't alter the table, there's nothing else to do here.
}
};
private PlaceDatabase placeDatabase;
private CurrentLocation currentLocation = null;
private String tag = getClass().getName();
//this is the data that we will fetch asynchronously
private MutableLiveData<List<PlaceDetails>> placeList;
public PlaceRepository(Context context) {
placeDatabase = PlaceDatabase.getDatabase(context);
//addMigrations(MIGRATION_1_2)
placeList =
new MutableLiveData<>();
}
public MutableLiveData<List<PlaceDetails>> getNearestPlacesFromAPI(String type, final String next_page_token, LatLng latLng) {
List<PlaceDetails> placeDetailsList = new ArrayList<>();
try {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<Example> call = apiService.getNearbyPlaces(type,
latLng.latitude + "," +
latLng.longitude, ApplicationData.PROXIMITY_RADIUS,
ApplicationData.PLACE_API_KEY, next_page_token);
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Call<Example> call, Response<Example> response) {
try {
Example example = response.body();
ApplicationData.NEXT_PAGE_URL = example.getNextPageToken();
// next_page_url = example.getNextPageToken();
LogMe.i(tag, "next_page_url:" + ApplicationData.NEXT_PAGE_URL);
if (example.getStatus().equals("OK")) {
LogMe.i("getNearbyPlaces::", " --- " + response.toString() +
response.message() + response.body().toString());
// This loop will go through all the results and add marker on each location.
for (int i = 0; i < example.getResults().size(); i++) {
Double lat = example.getResults().get(i).getGeometry().getLocation().getLat();
Double lng = example.getResults().get(i).getGeometry().getLocation().getLng();
String placeName = example.getResults().get(i).getName();
String vicinity = example.getResults().get(i).getVicinity();
String icon = example.getResults().get(i).getIcon();
String place_id = example.getResults().get(i).getPlaceId();
PlaceDetails placeDetails = new PlaceDetails();
if (example.getResults().get(i).getRating() != null) {
Double rating = example.getResults().get(i).getRating();
placeDetails.setRating(rating);
}
//List<Photo> photoReference = example.getResults().
// get(i).getPhotos();
placeDetails.setName(placeName);
placeDetails.setAddress(vicinity);
placeDetails.setLatitude(lat);
placeDetails.setLongitude(lng);
placeDetails.setIcon(icon);
placeDetails.setPlace_id(place_id);
//placeDetails.setPlace_type(place_type_title);
double value = ApplicationData.
DISTANCE_OF_TWO_LOCATION_IN_KM(latLng.latitude, latLng.longitude, lat, lng);
//new DecimalFormat("##.##").format(value);
placeDetails.setDistance(new DecimalFormat("##.##").format(value));
String ph = "";
if (example.getResults().
get(i).getPhotos() != null) {
try {
List<Photo> photos = example.getResults().
get(i).getPhotos();
//JSONArray array = new JSONArray(example.getResults().
//get(i).getPhotos());
//JSONObject jsonObj = new JSONObject(array.toString());
//ph = jsonObj.getString("photo_reference");
ph = photos.get(0).getPhotoReference();
//LogMe.i(tag, "\n" + ph);
} catch (Exception e) {
e.printStackTrace();
//placeDetails.setPicture_reference(ph);
//PLACE_DETAILS_LIST.add(placeDetails);
//LogMe.i(tag, "#### Exception Occureed ####");
ph = "";
//continue;
}
}
placeDetails.setPicture_reference(ph);
placeDetailsList.add(placeDetails);
placeList.postValue(placeDetailsList);
}
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<Example> call, Throwable t) {
Log.e("onFailure", t.toString());
}
});
} catch (RuntimeException e) {
//hideProgressDialog();
Log.d("onResponse", "RuntimeException is an error");
e.printStackTrace();
} catch (Exception e) {
Log.d("onResponse", "Exception is an error");
}
return placeList;
}
}
I precise code due to question simplicity.
Though you already use android-jetpack, take a look at Paging library. It's specially designed for building infinite lists using RecyclerView.
Based on your source code, I'd say that you need PageKeyedDataSource, here is some example which includes info about how to implement PageKeyedDataSource -
7 steps to implement Paging library in Android
If talking about cons of this approach:
You don't need anymore to observe list scrolling (library doing it for you), you just need to specify your page size in the next way:
PagedList.Config myPagingConfig = new PagedList.Config.Builder()
.setPageSize(50)
.build();
From documentation:
Page size: The number of items in each page.
Your code will be more clear, you'll get rid of your RecyclerView.OnScrollListener
ViewModel code will be shorter, it's will provide only PagedList:
#NonNull
LiveData<PagedList<ReviewSection>> getReviewsLiveData() {
return reviewsLiveData;
}

API request catches exception NULL response

I am using NYT's developers movie reviews API, and i am at the beginning where i just want to see a response. It appears that i get a NULL response which catches the exception that i will pinpoint on the code. " CharSequence text = "There was an error. Please try again";" to help you find it. Could someone please tell me what causes this problem.
NYT Documentation Link http://developer.nytimes.com/movie_reviews_v2.json#/Documentation/GET/critics/%7Bresource-type%7D.json
public class MainActivity extends AppCompatActivity {
private final String site = "https://api.nytimes.com/svc/movies/v2/reviews/search.json?query=";
public int count;
public int i;
public int j;
public int k;
public int n;
public int comas;
public int ingadded;
public String web2 = "";
public String istos;
public ArrayList<String> mylist = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button next = (Button) findViewById(R.id.button);
final EditText edit_text = (EditText) findViewById(R.id.ing);
final TextView show_ing = (TextView) findViewById(R.id.show_ing);
final Button done = (Button) findViewById(R.id.button3);
final Button refresh = (Button) findViewById(R.id.refresh);
final Button delete = (Button) findViewById(R.id.delete);
final ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
//done move to next activity
done.setOnClickListener(new View.OnClickListener() {
#Override
//CHECK IF TEXT BOX IS EMPTY
public void onClick(View view) {
web2 = edit_text.getText().toString();
//check if there are ingredients added
if (web2 == "") {
Context context = getApplicationContext();
CharSequence text = "Search Bar is Empty!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Dialog.dismiss();
}
else {
//IF NOT CREATE THE LINK AND SEND IT TO LongOperation
web2 = edit_text.getText().toString();
//create link - MAYBE THE WAY API KEY MUST BE CALLED?
istos = site + web2 + "?api-key=xxxxxxxxxxxx";
Log.v("Showme=", istos);
web2 = "";
// WebServer Request URL
String serverURL = istos;
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
}
});
edit_text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
edit_text.setHint("");
else
edit_text.setHint("Type the title of the movie");
}
});
private class LongOperation extends AsyncTask<String, String, Void> {
// Required initialization
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private Integer count;
private int add = 1;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView jsonParsedname = (TextView) findViewById(R.id.jsonParsedname1);
ArrayList<ArrayList<Integer>> numArray = new ArrayList<ArrayList<Integer>>();
int sizeData = 0;
protected void onPreExecute() {
//Start Progress Dialog (Message)
Dialog.setMessage("Finding Movies..");
Dialog.show();
try {
// Set Request parameter
data = "&" + URLEncoder.encode("data", "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception ex) {
Error = ex.getMessage();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
/*****************************************************/
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
Context context = getApplicationContext();
CharSequence text = "There was an error. Please try again";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Dialog.dismiss();
} else {
JSONObject jsonResponse;
try {
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse = new JSONObject(Content);
if (jsonResponse == null) {
jsonParsedname.setText("Wrong Input");
}
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("results");

How to implement a endless Recylerview?

How to implement a endless Recylerview?
This is Activity code:
public class ShopList extends AppCompatActivity {
RecyclerView rview;
RatingBar ratingbar;
private String `urlParameters`;
Recyclerviewshopl adapter;
String category;
JSONArray arr = null;
private Boolean Isinternetpresent = false;
ConnectionDetector cd;
String cat;
ProgressDialog dialog;
String lat,lon;
TextView nodata;
ImageView oops;
double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shop_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ratingbar = (RatingBar) findViewById(R.id.ratingbar);
List<Itemshopl> rowListItem = getAllItemList();
rview=(RecyclerView)findViewById(R.id.recycleshop);
nodata=(TextView)findViewById(R.id.nodata);
oops=(ImageView)findViewById(R.id.oops);
nodata.setVisibility(View.GONE);
oops.setVisibility(View.GONE);
// LayerDrawable stars = (LayerDrawable) ratingbar.getProgressDrawable();
//stars.getDrawable(5).setColorFilter(Color.parseColor("#26ce61"),
// PorterDuff.Mode.SRC_ATOP);
// stars.getDrawable(1).setColorFilter(Color.YELLOW, PorterDuff.Mode.SRC_ATOP);
/* RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, //width
ViewGroup.LayoutParams.WRAP_CONTENT);//height
rview.setLayoutParams(lp);*/
Bundle extras = getIntent().getExtras();
cat = extras.getString("category");
lat=extras.getString("lat");
lon=extras.getString("lon");
System.out.println("gr++"+cat);
cd = new ConnectionDetector(getApplicationContext());
Isinternetpresent = cd.isConnectingToInternet();
// onBackPressed();
if(Isinternetpresent)
{
shoplist tasku=new shoplist();
tasku.execute(new String[]{"http://abc**.com/****/getshoplist"});
}else{
// Toast.makeText(UserProfileActivity.this,"No Internet connection",Toast.LENGTH_SHORT).show();
showAlertDialog(ShopList.this, "No Internet Connection", "You don't have internet connection.", false);
}
}
public void showAlertDialog(Context context, String title, String message, Boolean status)
{
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
// alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
});
alertDialog.show();
}
private List<Itemshopl> getAllItemList() {
List<Itemshopl> allItems = new ArrayList<Itemshopl>();
allItems.add(new Itemshopl());
allItems.add(new Itemshopl());
allItems.add(new Itemshopl());
allItems.add(new Itemshopl());
return allItems;
}
private class shoplist extends AsyncTask<String, String, List<Itemshopl>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(ShopList.this, "Loading", "Please Wait...", true);
dialog.show();
}
#Override
protected List<Itemshopl> doInBackground(String... urls) {
URL url;
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
urlParameters = "&cat=" + URLEncoder.encode(cat, "UTF-8")+
"&lat="+ URLEncoder.encode(lat, "UTF-8")+
"&lon="+ URLEncoder.encode(lon, "UTF-8");
url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
String finalJson = buffer.toString();
List<Itemshopl> itemshoplist = new ArrayList<>();
arr = new JSONArray(finalJson);
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
/// String state = obj.getString("status");
Itemshopl model = new Itemshopl();
model.setName(obj.getString("shopname"));
model.setcat1(obj.getString("subcat1"));
model.setcat2(","+obj.getString("subcat2"));
model.setcat3(","+obj.getString("subcat3"));
model.setcat4(","+obj.getString("subcat4"));
model.setThumbnailUrl(obj.getString("logo"));
model.setid(obj.getString("id"));
model.setrating(obj.getString("rating"));
model.setreview(obj.getString("reviews")+"Reviews");
model.setcat(obj.getString("category"));
itemshoplist.add(model);
}
// cacheThis.writeObject(ShopList.this, "name", "hai");
return itemshoplist;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<Itemshopl> detailsModels) {
super.onPostExecute(detailsModels);
dialog.dismiss();
if (detailsModels != null && detailsModels.size() > 0) {
nodata.setVisibility(View.GONE);
oops.setVisibility(View.GONE);
rview=(RecyclerView)findViewById(R.id.recycleshop);
rview.setHasFixedSize(true);
adapter = new Recyclerviewshopl(getApplicationContext(), detailsModels);
rview.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
rview.setAdapter(adapter);
}else
{
nodata.setVisibility(View.VISIBLE);
oops.setVisibility(View.VISIBLE);
}
}
}}
Adapter:
public class Recyclerviewshopl extends RecyclerView.Adapter<Recyclerviewshopl.ViewHolder> {
private List<Itemshopl> itemList;
private Context context;
public Recyclerviewshopl(Context context, List<Itemshopl> itemList) {
this.itemList = itemList;
this.context = context;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.name.setText(itemList.get(position).getName());
holder.icons.setImageResource(itemList.get(position).getPhoto());
holder.cat1.setText(itemList.get(position).getcat1());
holder.cat2.setText(itemList.get(position).getcat2());
holder.cat3.setText(itemList.get(position).getcat3());
holder.cat4.setText(itemList.get(position).getcat4());
holder.id.setText(itemList.get(position).getid());
// holder.review.setText(itemList.get(position).getreview());
holder.image.setText(itemList.get(position).getimg());
Glide.with(context).load(itemList.get(position).getThumbnailUrl()).into(holder.icons );
holder.phone.setText(itemList.get(position).getPhone());
holder.cat.setText(itemList.get(position).getcat());
if(itemList.get(position).getrating().equals(""))
{
itemList.get(position).getrating().equals("0");
} else {
//int value= Integer.parseInt(holder.rate.toString());
holder.rate.setRating(Float.parseFloat(itemList.get(position).getrating()));
}
holder.review.setText(itemList.get(position).getreview());
}
public ViewHolder onCreateViewHolder(ViewGroup parent, int i)
{
View layoutview = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardshoplist, null);
ViewHolder sg = new ViewHolder(layoutview);
return sg;
}
#Override
public int getItemCount() {
return this.itemList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name, cat1,cat2,cat3,cat4,review,image,id,phone,cat;
ImageView photo;
ImageView icons;
RatingBar rate;
public ViewHolder(final View itemView) {
super(itemView);
icons = (ImageView) itemView.findViewById(R.id.img1);
name = (TextView) itemView.findViewById(R.id.shopname);
cat=(TextView)itemView.findViewById(R.id.cat);
cat1=(TextView)itemView.findViewById(R.id.cat1);
cat2=(TextView)itemView.findViewById(R.id.cat2);
cat3=(TextView)itemView.findViewById(R.id.cat3);
cat4=(TextView)itemView.findViewById(R.id.cat4);
review=(TextView)itemView.findViewById(R.id.review);
image=(TextView)itemView.findViewById(R.id.img);
id=(TextView)itemView.findViewById(R.id.idvalue);
phone=(TextView)itemView.findViewById(R.id.phone);
rate=(RatingBar)itemView.findViewById(R.id.ratingbar);
itemView.setOnClickListener(new View.OnClickListener() {
int pos = getAdapterPosition();
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
Intent in = new Intent(v.getContext(),ShopeProfile.class);
in.putExtra("id",id.getText().toString());
in.putExtra("shopname",name.getText().toString());
in.putExtra("phone",phone.getText().toString());
in.putExtra("rate",rate.getRating());
in.putExtra("cat",cat.getText().toString());
v.getContext().startActivity(in);
}
});
}
}
}

How to send file with file name by use wifidirect?

I use wifidirect to send file,but I can't get the file name(include .jpg or .mp3),and sent it,it always null.
i'm using wifidirect demo provided Android Developers
I use
File f = new File(uri.getPath());
fileName = f.getName();
and
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ "Wifidirect" + "/" + fileName);
but fileName is alwas null
public class DeviceDetailFragment extends Fragment implements ConnectionInfoListener {
protected static final int CHOOSE_FILE_RESULT_CODE = 20;
private View mContentView = null;
private WifiP2pDevice device;
private WifiP2pInfo info;
//private static WiFiDirectBundle bundle = new WiFiDirectBundle();
ProgressDialog progressDialog = null;
private static String fileName;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mContentView = inflater.inflate(R.layout.device_detail, null);
mContentView.findViewById(R.id.btn_connect).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
config.wps.setup = WpsInfo.PBC;
config.groupOwnerIntent = 15;
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
progressDialog = ProgressDialog.show(getActivity(), "Press back to cancel",
"Connecting to :" + device.deviceAddress, true, true
// new DialogInterface.OnCancelListener() {
//
// #Override
// public void onCancel(DialogInterface dialog) {
// ((DeviceActionListener) getActivity()).cancelDisconnect();
// }
// }
);
((DeviceActionListener) getActivity()).connect(config);
}
});
mContentView.findViewById(R.id.btn_disconnect).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
((DeviceActionListener) getActivity()).disconnect();
}
});
mContentView.findViewById(R.id.btn_start_client).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// Allow user to pick an image from Gallery or other
// registered apps
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, CHOOSE_FILE_RESULT_CODE);
}
});
return mContentView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// User has picked an image. Transfer it to group owner i.e peer using
// FileTransferService.
Uri uri = data.getData();
File f = new File(uri.getPath());
fileName = f.getName();
TextView statusText = (TextView) mContentView.findViewById(R.id.status_text);
statusText.setText("Sending: " + uri);
Log.d(WiFiDirectActivity.TAG, "Intent----------- " + uri);
Intent serviceIntent = new Intent(getActivity(), FileTransferService.class);
serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
info.groupOwnerAddress.getHostAddress());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
getActivity().startService(serviceIntent);
}
#Override
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
this.info = info;
this.getView().setVisibility(View.VISIBLE);
// The owner IP is now known.
TextView view = (TextView) mContentView.findViewById(R.id.group_owner);
view.setText(getResources().getString(R.string.group_owner_text)
+ ((info.isGroupOwner == true) ? getResources().getString(R.string.yes)
: getResources().getString(R.string.no)));
// InetAddress from WifiP2pInfo struct.
view = (TextView) mContentView.findViewById(R.id.device_info);
view.setText("Group Owner IP - " + info.groupOwnerAddress.getHostAddress());
// After the group negotiation, we assign the group owner as the file
// server. The file server is single threaded, single connection server
// socket.
if (info.groupFormed && info.isGroupOwner) {
new FileServerAsyncTask(getActivity(), mContentView.findViewById(R.id.status_text))
.execute();
} else if (info.groupFormed) {
// The other device acts as the client. In this case, we enable the
// get file button.
mContentView.findViewById(R.id.btn_start_client).setVisibility(View.VISIBLE);
((TextView) mContentView.findViewById(R.id.status_text)).setText(getResources()
.getString(R.string.client_text));
}
// hide the connect button
mContentView.findViewById(R.id.btn_connect).setVisibility(View.GONE);
}
/**
* Updates the UI with device data
*
* #param device the device to be displayed
*/
public void showDetails(WifiP2pDevice device) {
this.device = device;
this.getView().setVisibility(View.VISIBLE);
TextView view = (TextView) mContentView.findViewById(R.id.device_address);
view.setText(device.deviceAddress);
view = (TextView) mContentView.findViewById(R.id.device_info);
view.setText(device.toString());
}
/**
* Clears the UI fields after a disconnect or direct mode disable operation.
*/
public void resetViews() {
mContentView.findViewById(R.id.btn_connect).setVisibility(View.VISIBLE);
TextView view = (TextView) mContentView.findViewById(R.id.device_address);
view.setText(R.string.empty);
view = (TextView) mContentView.findViewById(R.id.device_info);
view.setText(R.string.empty);
view = (TextView) mContentView.findViewById(R.id.group_owner);
view.setText(R.string.empty);
view = (TextView) mContentView.findViewById(R.id.status_text);
view.setText(R.string.empty);
mContentView.findViewById(R.id.btn_start_client).setVisibility(View.GONE);
this.getView().setVisibility(View.GONE);
}
/**
* A simple server socket that accepts connection and writes some data on
* the stream.
*/
public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
private Context context;
private TextView statusText;
//String FileName = "bundle.fileName";
/**
* #param context
* #param statusText
*/
public FileServerAsyncTask(Context context, View statusText) {
this.context = context;
this.statusText = (TextView) statusText;
}
#Override
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
Log.d(WiFiDirectActivity.TAG, "Server: Socket opened");
Socket client = serverSocket.accept();
Log.d(WiFiDirectActivity.TAG, "Server: connection done");
/*final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ "Wifidirect" + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");*/
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ "Wifidirect" + "/" + fileName);
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString());
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(String result) {
if (result != null) {
statusText.setText("File copied - " + result);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "image/*");
context.startActivity(intent);
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
statusText.setText("Opening a server socket");
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
} catch (IOException e) {
Log.d(WiFiDirectActivity.TAG, e.toString());
return false;
}
return true;
}
}
File f = new File(uri.getPath());
fileName = f.getName();
This part of code in your app will get executed - if device acts as client
and
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ "Wifidirect" + "/" + fileName);
this part of code in your app will get executed - if device acts as server (in this case GO) but fileName is always null
Since filename is initialized to "null" , on the server device this will be null.
FileServerAsyncTask is created only on GO( server ) as per the code.
In android sample code file transfer is working only from client to server. In this code user can do file sharing in both directions i.e client to server as well as server to client.
You can see this link.
How can I transfer files between Android devices using Wi-Fi Direct?

Current location on map using WIFI in android

i just need to find the current location on maps using WIFI.I used tha below code to do that.
My code:
public class LocationActivity extends MapActivity implements LocationListener {
private MapView mapView;
private LocationManager locationManager;
private String latitude,longtitude;
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getIntent().getExtras();
latitude = bundle.getString("latitude");
longtitude = bundle.getString("longtitude");
setContentView(R.layout.locationtab);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
locationIdentifier();
}
private void createMyLocOverlay(Double latitude, Double longtitude) {
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(
R.drawable.mylocation);
GeoPoint point = new GeoPoint((int) (latitude * 1E6),
(int) (longtitude * 1E6));
OverlayItem overlayitem = new OverlayItem(point, null, "You are here!");
MyLocationOverlay itemizedoverlay = new MyLocationOverlay(drawable,
this);
itemizedoverlay.addOverlay(overlayitem);
MyLocationOverlay overlayToRemove = null;
for (Overlay overlay : mapOverlays) {
if (overlay instanceof MyLocationOverlay) {
overlayToRemove = (MyLocationOverlay) overlay;
}
}
if (overlayToRemove != null) {
mapOverlays.remove(overlayToRemove);
}
mapOverlays.add(itemizedoverlay);
}
public void locationIdentifier() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria,true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
createMyLocOverlay(location.getLatitude(), location.getLongitude());
Toast.makeText(
this,
"Latitude : " + location.getLatitude() + " : Longtitude : "
+ location.getLongitude(), Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(this, "Latitude/Longtitude not found",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
createMyLocOverlay(location.getLatitude(), location.getLongitude());
Toast.makeText(
this,
"LocationChanged Latitude : " + location.getLatitude()
+ " Longtitude : " + location.getLongitude(),
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Location is null", Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider, Toast.LENGTH_LONG)
.show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
How could i check it on emulator whether its working or not.?
For now, It is not possible to simulate it using emulator because it is simply doesn't support it. As alternative, you may put a flag constant (e.g. DEBUG=false/true) then if DEBUG=true, use the constant location otherwise use WIFI location.
Or use location provider which can support IP Address location. Which you can use as alternative if DEBUG=true.