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);
}
});
}
}
}
Related
My code is here; I was selecting PDF files from a SD card or internal phone memory using the showFileChooser() method then from onActivityResult(), the files go to mergePdfFiles(View view) method, and from there the files go to createPdf(String[] srcs).
Here is the complete code of my activity:
//Below is onCreate();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mergedpdf);
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, locations);
// public void fileSelected(File file ) {
// locations.add(file.toString());
// adapter.notifyDataSetChanged();
// }
NewText = (TextView)findViewById(R.id.textView);
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
listView = (ListView)findViewById(R.id.list_items);
btn = (ImageView) findViewById(R.id.imageView8);
btnconvert = (ImageView) findViewById(R.id.imageView11);
btnconvert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// btTag=((Button)v).getTag().toString();
try {
createPdf( locations);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Toast.makeText(Mergedpdf.this, "button clicked", Toast.LENGTH_SHORT).show();
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// btTag=((Button)v).getTag().toString();
showFileChooser();
NewText.setText("Below Files are Selected");
}
});
}
//this is mergedfiles();
public void mergePdfFiles(View view){
Toast.makeText(Mergedpdf.this, "merge function", Toast.LENGTH_SHORT).show();
try {String[] srcs= new String[locations.size()];
for(int i = 0;i<locations.size();i++) {
srcs[i] = locations.get(i);
}
// String[] srcs = {txt1.getText().toString(), txt2.getText().toString()};
createPdf(srcs);
}catch (Exception e){e.printStackTrace();}
}
//This method create merged pdf file
public void createPdf (String[] srcs) {
try {
// Create document object
File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Merged-PDFFiles");
if (!docsFolder.exists()) {
docsFolder.mkdir();
Log.i(TAG, "Created a new directory for PDF");
}
Date date = new Date();
#SuppressLint("SimpleDateFormat") final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date);
Document document = new Document();
// pdfCopy = new File(docsFolder.getAbsolutePath(),pdf+"Images.pdf");
// Document document = new Document();
//PdfWriter.getInstance(document, output);
// Create pdf copy object to copy current document to the output mergedresult file
PdfCopy copy = new PdfCopy(document, new FileOutputStream(docsFolder + "/" + timeStamp +"combine.pdf"));
Toast.makeText(Mergedpdf.this, "merged pdf saved", Toast.LENGTH_SHORT).show();
// Open the document
document.open();
PdfReader pr;
int n;
for (int i = 0; i < srcs.length; i++) {
// Create pdf reader object to read each input pdf file
pr = new PdfReader(srcs[i].toString());
// Get the number of pages of the pdf file
n = pr.getNumberOfPages();
for (int page = 1; page <= n; page++) {
// Import all pages from the file to PdfCopy
copy.addPage(copy.getImportedPage(pr, page));
}
}
document.close(); // close the document
} catch (Exception e) {
e.printStackTrace();
}
}
//below is showfilechooser(); method
private void showFileChooser () {
Log.e("AA", "bttag=" + btTag);
String folderPath = Environment.getExternalStorageDirectory() + "/";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
Uri myUri = Uri.parse(folderPath);
intent.setDataAndType(myUri, "application/pdf");
Intent intentChooser = Intent.createChooser(intent, "Select a file");
startActivityForResult(intentChooser,PICKFILE_RESULT_CODE);
}
//below is onActivityResult(); method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
if (requestCode == PICKFILE_RESULT_CODE) {
if (resultCode == RESULT_OK) {
String FilePath = data.getData().getPath();
locations.add(FilePath);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.listview,locations);
listView.setAdapter(adapter);
}
}
}
}
//And my declared variables before oncreate().
public com.itextpdf.text.Document Document;
public PdfCopy Copy;
public ByteArrayOutputStream ms;
TextView NewText;
private TextView txt1;
private Button bt1, bt2,bt3;
private Handler handler;
ListView listView;
ArrayList<String> locations = new ArrayList<>();
ArrayAdapter<String> adapter;
ImageView btn, btnconvert, btn3;
private static final String TAG = "PdfCreator";
private final int PICKFILE_RESULT_CODE=10;
private String btTag = "";
i am using volley to fetch data from database.I always get null pointer error. I don't know whats the error. it always executes onErrorResponse() (error.null) and shows this in my logcat
BasicNetwork.performRequest: Unexpected response code 301
here is my java method to fetch data from php file .
private void fetchChatThread() {
StringRequest strReq = new StringRequest(Request.Method.POST,
EndPoints.chatMessages, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Load_datato_list load_data_tolist = new Load_datato_list();
load_data_tolist.execute(obj);
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Messages messages=new Messages();
error.printStackTrace();
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, " Try Again fetch error" + networkResponse);
Toast.makeText(Chat_Rooms.this, messages.getSender_id(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> myparams = new HashMap<String, String>();
try {
myparams.put("sender_userid", sender_userid);
myparams.put("reciver_id", String_username.reciver_user_id);
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG, "Params: " + myparams.toString());
return myparams;
}
};
//Adding request to request queue
addToRequestQueue(strReq);
}
here is my private that loads data from php to objects
private class Load_datato_list extends AsyncTask<JSONObject, Void, ArrayList<Messages>> {
#Override
protected ArrayList<Messages> doInBackground(JSONObject[] params) {
JSONObject obj = params[0];
try {
JSONArray commentsObj = obj.getJSONArray("messages");
for (int i = 0; i < commentsObj.length(); i++) {
JSONObject commentObj = (JSONObject) commentsObj.get(i);
String commentId = commentObj.getString("id");
String commentText = commentObj.getString("message");
String createddate = commentObj.getString("date");
String commentuser_id = commentObj.getString("user_id_fk");
URL url;
Bitmap image, image1;
try {
url = new URL(Base_URL.BASE_URL_IMAGES + "user_profile_pictures" + commentuser_id + ".jpg");
image1 = BitmapFactory.decodeStream(url.openStream());
image = getResizedBitmap(image1, 50);
} catch (Exception e) {
image = null;
e.printStackTrace();
}
Users user;
user = new Users(commentuser_id, String_username.user_name, image);
Messages message = new Messages();
message.setId(commentId);
message.setMessage(commentText);
message.setCreatedAt(createddate);
message.setSender_id(commentuser_id);
message.setUser(user);
messageArrayList.add(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return messageArrayList;
}
#Override
protected void onPostExecute(ArrayList<Messages> messageArrayList) {
Collections.reverse(messageArrayList);
chatroom_adapter.notifyDataSetChanged();
if (chatroom_adapter.getItemCount() > 1) {
rec_chatBubble.getLayoutManager().smoothScrollToPosition(rec_chatBubble, null, chatroom_adapter.getItemCount() - 1);
}
}
}
TRY THIS
private void fetchChatThread(final String count) {
StringRequest strReq = new StringRequest(Request.Method.POST,
EndPoints.chatMessages, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Log.d("response error", response);
Load_datato_list load_data_tolist = new Load_datato_list();
load_data_tolist.execute(obj);
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Messages messages = new Messages();
error.printStackTrace();
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, " Try Again fetch error" + networkResponse);
}
}) {
#Override
protected HashMap<String, String> getParams() {
HashMap<String, String> myparams = new HashMap<String, String>();
try {
myparams.put("sender_userid", sender_userid);
myparams.put("reciver_id", String_username.reciver_user_id);
myparams.put("count", count);
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG, "Params: " + myparams.toString());
return myparams;
}
};
//Adding request to request queueok
addToRequestQueue(strReq);
}
AND THIS
private class Load_datato_list extends AsyncTask<JSONObject, Void, ArrayList<Messages>> {
#Override
protected ArrayList<Messages> doInBackground(JSONObject[] params) {
messageArrayList.clear();
JSONObject obj = params[0];
try {
JSONArray commentsObj = obj.getJSONArray("messages");
for (int i = 0; i < commentsObj.length(); i++) {
JSONObject commentObj = (JSONObject) commentsObj.get(i);
String Id = commentObj.getString("id");
String Text = commentObj.getString("message");
String date = commentObj.getString("date");
String yuser_id = commentObj.getString("user_id");
Messages message = new Messages();
message.setId(Id);
message.setMessage(Text);
message.setCreatedAt(date);
message.setSender_id(yuser_id);
messageArrayList.add(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return messageArrayList;
}
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.
I build table. I want to add data from active window. But a.getTabNum() and rest of returned vatiables have the value of null
Here is my code:
JButton add = new JButton();
add.setText("+");
add.setHorizontalAlignment(SwingConstants.TRAILING);
panel.add(add);
//When user clicks he can add new employee
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
AddEmp a = new AddEmp();
a.setSize(400,140);
a.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
a.setVisible(true);
String post = a.getPost();
String nameSurname = a.getNameSurname();
String tabNum= a.getTabNum();
Connection connect = null;
PreparedStatement statement1 = null;
try {
connect = DriverManager
.getConnection("jdbc:mysql://localhost/tabel?user=root&password=4499669");
statement1 = connect
.prepareStatement("insert into employee(tab_num, name_surname, position, id_dept) values(?, ?, ?, ?)");
int a1= Integer.parseInt(tabNum);
statement1.setInt(1, a1);
statement1.setString(2,nameSurname);
statement1.setString(3, post);
statement1.setInt(4, num);
statement1.executeUpdate();
// / List of departments
// ////////////////////////////////////////////////////////////////
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
connect.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
});
here is ma AddEmp class:`public class AddEmp extends JFrame{
private static final long serialVersionUID = 1L;
JTextField a = new JTextField(30);
JTextField b = new JTextField(27);
JTextField c = new JTextField(23);
AddEmp self = this;
JLabel a1 = new JLabel("Ф.И.О");
JLabel b1 = new JLabel("Должность");
JLabel c1 = new JLabel("Табельный номер");
JButton o = new JButton("OK");
public AddEmp(){
super("Добавление сотрудника");
setResizable(false);
JPanel p = new JPanel();
p.add(a1);
p.add(a);
p.add(b1);
p.add(b);
p.add(c1);
p.add(c);
o.setHorizontalAlignment(SwingConstants.RIGHT);
p.add(o);
getContentPane().add(p, BorderLayout.CENTER);
o.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
JOptionPane.showMessageDialog(null, "Сотрудник добавлен");
self.setVisible(false);
self.dispose();
}catch(Exception e){
e.printStackTrace();
}
}
});
}
public String getPost() {
return b.getText();
}
public String getNameSurname() {
return a.getText();
}
public String getTabNum() {
return c.getText();
}
}`
I am trying to create an app that uses the panning and zooming features on the map. I have spent a lot of time trying to implement this. I first tried to create an on touch method inside the MapActivity, but I soon realized it would be a little more than that. I found some code that I tried to implement that created a subclass of a mapview and ran into some issues with it. I need some help with panning around the map. Everywhere I try to clear and display the overlay causes problems. Either the overlays get removed and displayed at the wrong place, or a loop is created causing flashing. Please let me know what I need to do to get this working. I realized that I may need to override the onScroll method if there is one instead of the onTouch method. Right now it is pretty buggy I need some help, so that I can make it bug free. Let me know if my thinking is correct. I need to get this up on the market right away. Here is my code. Thanks in advance.
//MapActivity class
//Package name omitted
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class MapActivityNearby extends MapActivity {
private static final String TAG = "MAPACTIVITY";
double lat;
double lng;
EnhancedMapView mv;
ArrayList<MapItem> allCats;
private static final String PREF_NAME = "cookie";
private float latMax;
private float latMin;
private float longMax;
private float longMin;
GeoPoint p;
private List<Overlay> mapOverlays;
private MyItemizedOverlay itemizedOverlay;
boolean waitTime = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_nearby);
LinearLayout ll = (LinearLayout) findViewById(R.id.maplayout);
mv = new EnhancedMapView(this, "0ieXSx8GEy9Hm7bCZMLckus7pmPKg0w8kelRO_g");
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
mv.setLayoutParams(lp);
mv.setClickable(true);
mv.setBuiltInZoomControls(true);
mv.setOnZoomChangeListener(new EnhancedMapView.OnZoomChangeListener() {
#Override
public void onZoomChange(MapView view, int newZoom, int oldZoom) {
Log.v("test", "zoom center changed");
if (isNetworkAvailable(MapActivityNearby.this))
{
LogIn log = new LogIn();
log.execute(mv);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(MapActivityNearby.this);
builder.setMessage("No network connection. Please try again when your within coverage area.")
.setTitle("Network Connection")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//close dialog
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
});
mv.setOnPanChangeListener(new EnhancedMapView.OnPanChangeListener() {
public void onPanChange(MapView view, GeoPoint newCenter, GeoPoint oldCenter) {
Log.v("test", "pan center changed");
if (isNetworkAvailable(MapActivityNearby.this))
{
LogIn log = new LogIn();
log.execute(mv);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(MapActivityNearby.this);
builder.setMessage("No network connection. Please try again when your within coverage area.")
.setTitle("Network Connection")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//close dialog
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
});
ll.addView(mv);
SharedPreferences cookies = getSharedPreferences(PREF_NAME,
Context.MODE_PRIVATE);
lat = Double.parseDouble(cookies.getString("lat", "0"));
lng = Double.parseDouble(cookies.getString("lng", "0"));
GeoPoint p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
MapController mapControl = mv.getController();
mapControl.setCenter(p);
mapControl.setZoom(11);
}
public void onResume()
{
super.onResume();
if (isNetworkAvailable(MapActivityNearby.this))
{
LogIn log = new LogIn();
log.execute(mv);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(MapActivityNearby.this);
builder.setMessage("No network connection. Please try again when your within coverage area.")
.setTitle("Network Connection")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//close dialog
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
public void plotPoints(ArrayList<MapItem> i) {
mapOverlays = mv.getOverlays();
// first overlay
Drawable drawable;
drawable = getResources().getDrawable(R.drawable.marker);
itemizedOverlay = new MyItemizedOverlay(drawable, mv);
mapOverlays.add(itemizedOverlay);
for (MapItem x : i) {
GeoPoint point = new GeoPoint((int) (x.getLat() * 1E6),
(int) (x.getLng() * 1E6));
OverlayItem overlayItem = new OverlayItem(point,
x.getTitle(), x.getSubtitle());
itemizedOverlay.addOverlay(overlayItem);
}
}
private class LogIn extends AsyncTask<EnhancedMapView, Void, Boolean> {
String result = "";
InputStream is;
#Override
protected void onPreExecute() {
}
#Override
protected Boolean doInBackground(EnhancedMapView...params) {
if (!(mv.getOverlays().isEmpty()))
{
mv.getOverlays().clear();
}
int maxCount = 100;
EnhancedMapView mapView = params[0];
for (int i = 0; i < maxCount; i++)
{
p = mapView.getMapCenter();
float latCenter = (float) (p.getLatitudeE6()) / 1000000;
float longCenter = (float) (p.getLongitudeE6()) / 1000000;
float latSpan = (float) (mapView.getLatitudeSpan()) / 1000000;
float longSpan = (float) (mapView.getLongitudeSpan()) / 1000000;
latMax = latCenter + (latSpan/2);
latMin = latCenter - (latSpan/2);
longMax = longCenter + (longSpan/2);
longMin = longCenter - (longSpan/2);
if (latMin == latMax)
{
try
{
Thread.sleep(80);
}
catch(InterruptedException e)
{
}
}
else
{
p = mapView.getMapCenter();
latCenter = (float) (p.getLatitudeE6()) / 1000000;
longCenter = (float) (p.getLongitudeE6()) / 1000000;
latSpan = (float) (mapView.getLatitudeSpan()) / 1000000;
longSpan = (float) (mapView.getLongitudeSpan()) / 1000000;
latMax = latCenter + (latSpan/2);
latMin = latCenter - (latSpan/2);
longMax = longCenter + (longSpan/2);
longMin = longCenter - (longSpan/2);
break;
}
}
log(latMin);
log(latMax);
try {
final String catURL = "url goes here";
log(catURL.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(catURL);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
waitTime = true;
nameValuePairs.add(new BasicNameValuePair("PHPSESSID", getCookie()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
result = convertStreamToString();
log(result);
allCats = new ArrayList<MapItem>();
JSONObject object = new JSONObject(result);
JSONArray temp = object.getJSONArray("l");
log("Starting download");
log(temp.length());
long start = System.currentTimeMillis();
for (int k = 0; k < temp.length(); k++) {
JSONObject j = temp.getJSONObject(k);
MapItem c = new MapItem();
c.setObject_id(j.getInt("object_id"));
c.setTitle(j.getString("title"));
c.setColor(j.getString("color"));
c.setLat(j.getDouble("lat"));
c.setLng(j.getDouble("lng"));
c.setSubtitle(j.getString("subtitle"));
allCats.add(c);
log(allCats.toString());
}
long end = System.currentTimeMillis();
log("Download Took: " + (end - start) / 1000 + " seconds.");
// log(allCats.toString());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
// pBar.setVisibility(View.GONE);
plotPoints(allCats);
}
private String convertStreamToString() {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
result.trim();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
}
public String getCookie() {
String cookie = "";
SharedPreferences cookies = getSharedPreferences(PREF_NAME,
Context.MODE_PRIVATE);
if (cookies.contains("cookie")) {
cookie = cookies.getString("cookie", "null");
}
return cookie;
}
private void log(Object obj) {
Log.d(TAG, TAG + " :: " + obj.toString());
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
// CustomMapView class
// package name omitted
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
public class EnhancedMapView extends MapView {
public interface OnZoomChangeListener {
public void onZoomChange(MapView view, int newZoom, int oldZoom);
}
public interface OnPanChangeListener {
public void onPanChange(MapView view, GeoPoint newCenter, GeoPoint oldCenter);
}
private EnhancedMapView _this;
// Set this variable to your preferred timeout
private long events_timeout = 500L;
private boolean is_touched = false;
private GeoPoint last_center_pos;
private int last_zoom;
private Timer zoom_event_delay_timer = new Timer();
private Timer pan_event_delay_timer = new Timer();
private EnhancedMapView.OnZoomChangeListener zoom_change_listener;
private EnhancedMapView.OnPanChangeListener pan_change_listener;
public EnhancedMapView(Context context, String apiKey) {
super(context, apiKey);
_this = this;
last_center_pos = this.getMapCenter();
last_zoom = this.getZoomLevel();
}
public EnhancedMapView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EnhancedMapView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setOnZoomChangeListener(EnhancedMapView.OnZoomChangeListener l) {
zoom_change_listener = l;
}
public void setOnPanChangeListener(EnhancedMapView.OnPanChangeListener l) {
pan_change_listener = l;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() == 1) {
is_touched = false;
} else {
is_touched = true;
}
return super.onTouchEvent(ev);
}
#Override
public void computeScroll() {
super.computeScroll();
if (getZoomLevel() != last_zoom) {
// if computeScroll called before timer counts down we should drop it and start it over again
zoom_event_delay_timer.cancel();
zoom_event_delay_timer = new Timer();
zoom_event_delay_timer.schedule(new TimerTask() {
#Override
public void run() {
zoom_change_listener.onZoomChange(_this, getZoomLevel(), last_zoom);
last_zoom = getZoomLevel();
}
}, events_timeout);
}
// Send event only when map's center has changed and user stopped touching the screen
if (!last_center_pos.equals(getMapCenter()) || !is_touched) {
pan_event_delay_timer.cancel();
pan_event_delay_timer = new Timer();
pan_event_delay_timer.schedule(new TimerTask() {
#Override
public void run() {
pan_change_listener.onPanChange(_this, getMapCenter(), last_center_pos);
last_center_pos = getMapCenter();
}
}, events_timeout);
}
}
}
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.google.android.maps.MapView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:apiKey="0TqoE_fzA3Pv-m8188NwttzIKcYBzhNJsYRJkKQ"
android:id="#+id/mapview"
android:clickable="true"
android:enabled="true"
/>
</LinearLayout>
<RelativeLayout
android:layout_width="35dip"
android:layout_marginTop="300dip"
android:layout_marginLeft="270dip"
android:layout_height="70dip"
android:background="#AA000000">
<TextView android:layout_height="20dip"
android:gravity="center" android:textStyle="bold"
android:textColor="#000000" android:textSize="20dip"
android:id="#+id/zoomButton1"
android:layout_width="100dip"
android:text="+" />
<TextView android:layout_height="20dip"
android:layout_below="#id/zoomButton1"
android:textStyle="bold"
android:textColor="#000000"
android:gravity="center"
android:textSize="20dip"
android:id="#+id/zoomButton2"
android:layout_width="80dip"
android:text="-" />
</RelativeLayout>
</RelativeLayout>
MyMapActivity
public class MyMapActivity extends MapActivity {
/** Called when the activity is first created. */
MapView mapView;
ZoomControls zoomControls;
MapController mapController;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView)findViewById(R.id.mapview);
System.out.println("oncreate");
mapView.setStreetView(true);
mapView.invalidate();
mapController = mapView.getController();
// zoom contrlos
int y=10;
int x=10;
/*MapView.LayoutParams lp;
lp = new MapView.LayoutParams(MapView.LayoutParams.WRAP_CONTENT,
MapView.LayoutParams.WRAP_CONTENT,
x, y,
MapView.LayoutParams.TOP_LEFT);
View zoomControls = mapView.getZoomControls();
mapView.addView(zoomControls, lp);
mapView.displayZoomControls(true);*/
/*zoomControls = (ZoomControls) findViewById(R.id.zoomControls1);
zoomControls.setOnZoomInClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mapController.zoomIn();
}
});
zoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mapController.zoomOut();
}
});*/
TextView zButton =(TextView)findViewById(R.id.zoomButton1);
TextView zButton1 =(TextView)findViewById(R.id.zoomButton2);
zButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mapController.zoomIn();
Toast.makeText(myMapActivity.this, "Zoomin", Toast.LENGTH_SHORT).show();
}
});
zButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mapController.zoomOut();
Toast.makeText(myMapActivity.this, "ZoomOUT", Toast.LENGTH_SHORT).show();
}
});
Double lat = 38.899049*1E6;
Double lng = -77.017593*1E6;
GeoPoint point = new GeoPoint(lat.intValue(),lng.intValue());
System.out.println("Points"+point);
mapController.setCenter(point);
mapController.setZoom(15);
mapController.animateTo(point);
// http://maps.google.com/maps?ie=UTF8&hl=en&layer=t&ll=38.899049,-77.017593&spn=0.268261,0.6427&z=11
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}