I am developing a new app that gets data from a local database and uploads it to the Cloud but, after some time, it shows a prompt that the app is not responding.
I have reviewed the logcat debugger log but can not identify the issue. I am using gennymotion as virtual device to test the app.
Can anyone help me resolve this?
public class MainActivity extends AppCompatActivity implements SmartScheduler.JobScheduledCallback,NavigationView.OnNavigationItemSelectedListener{
String str;
ProgressBar pb;
TextView textView;
private static final int JOB_ID = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private static final String JOB_PERIODIC_TASK_TAG = "io.hypertrack.android_scheduler_demo.JobPeriodicTask";
String Ip="";
String Interval="";
private String intervalInMillisEditText;
JSONArray jsonArray;
static final String UrlPost = "serverIp";
final String TenantId = "Specific string";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Progress bar code is here
pb = (ProgressBar) findViewById(R.id.progressBar);
pb.setVisibility(View.GONE);
//for the textView of loading...
textView = (TextView) findViewById(R.id.textView);
//nevigations
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//get the interval values from Database
LoadDatabaseData();
}
public void LoadDatabaseData(){
List<IpAddressInverval> listIp = IpAddressInverval.listAll(IpAddressInverval.class);
for (IpAddressInverval ips:listIp) {
Ip= ips.getIpAddress();
Interval = ips.getInterval();
System.out.println("Ip "+Ip);
System.out.println("Interval is "+Interval);
}
}
public void gotoServicePage(View view){
//get the interval values from Database
LoadDatabaseData();
// Button btnstart = (Button) findViewById(R.id.button);
// btnstart.setVisibility(View.GONE);
if(Ip.matches("") || Interval.matches("")) {
Toast.makeText(this, "Please Fill the Parametters", Toast.LENGTH_SHORT).show();
}
// if(Interval.matches("")){
//
// Toast.makeText(this, "Please Fill the Parametters", Toast.LENGTH_SHORT).show();
//
// }
else
{
// CallApi();
SmartScheduler jobScheduler = SmartScheduler.getInstance(this);
// Check if any periodic job is currently scheduled
if (jobScheduler.contains(JOB_ID)) {
removePeriodicJob();
return;
}
// Create a new job with specified params
Job job = createJob();
if (job == null) {
Toast.makeText(MainActivity.this, "Invalid paramteres specified. " +
"Please try again with correct job params.", Toast.LENGTH_SHORT).show();
return;
}
// Schedule current created job
if (jobScheduler.addJob(job)) {
Toast.makeText(MainActivity.this, "Job successfully added!", Toast.LENGTH_SHORT).show();
}
}
}
//call the api and get the data
public void CallApi(){
String AddressIp = "http://"+Ip+":5700/api/values";
new AsyncHttpClient().get(AddressIp, new TextHttpResponseHandler() {
#Override
public void onStart() {
// pb.setVisibility(View.VISIBLE);
textView.setVisibility(View.VISIBLE);
textView.setText("Loading....");
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Toast.makeText(MainActivity.this, responseString, Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
str= responseString;
// Toast.makeText(MainActivity.this, "Data Received", Toast.LENGTH_SHORT).show();
try {
SpliterStringMethod(str);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
pb.setVisibility(View.GONE);
textView.setVisibility(View.GONE);
}
});
}
//spli the strinh into the array
public void SpliterStringMethod(String values) throws IOException, JSONException {
//unquote the string for the data..
values = values.replaceAll("^\"|\"$", "");
//split on the baseis of '#'
String[] lineString = values.split("#");
for (int i = 0; i < lineString.length; i++) {
double idTicket = 0;
System.out.println(lineString[i]);
String[] valuesString = lineString[i].split(",");
System.out.println("inner loop");
//fETCH THE ID FROM DB if ticket exist then update else insert into it
Ticket ticket = new Ticket();
List<Ticket> num = ticket.find(Ticket.class, "TICKETNO = " + valuesString[3]);
if (num.size() != 0) {
for (Ticket item : num) {
System.out.println("Fetching the id= " + item.getId());
idTicket = item.getId();
}
}
if (idTicket == 0) {
Ticket newTicket = new Ticket(Integer.parseInt(valuesString[1]), Integer.parseInt(valuesString[2])
, Integer.parseInt(valuesString[3]), Integer.parseInt(valuesString[4]),
Integer.parseInt(valuesString[5]));
newTicket.save();
System.out.println("Ticket Saved!..");
} else {
//update queue id
Ticket newqueuid = Ticket.findById(Ticket.class, (int) idTicket);
newqueuid.setPosition_in_queue(Integer.parseInt(valuesString[5])); // modify the values
newqueuid.save(); // updates the previous entry with new values.
System.out.println("Ticket Updated!..");
idTicket = 0;
}
}
}
//fetch the data from the Database
public void getTableData(){
//call the ticket table to get the values
List<Ticket> ticketAll = Ticket.listAll(Ticket.class);
jsonArray = new JSONArray();
for(int i=0;i<ticketAll.size();i++)
{
// JSONObject jGroup1 = new JSONObject();
Map jGroup1 = new LinkedHashMap();
jGroup1.put("track_no",ticketAll.get(i).getTrack_no());
jGroup1.put("time_no",ticketAll.get(i).getTime_no());
jGroup1.put("ticket_no",ticketAll.get(i).getTicket_no());
jGroup1.put("branch_id",ticketAll.get(i).getBranch_id());
jGroup1.put("position_in_queue",ticketAll.get(i).getPosition_in_queue());
jsonArray.put(new Gson().toJson(jGroup1, Map.class));
}
String str = POST(UrlPost,"");
}
public String POST(String url, String json){
enableStrictMode();
HttpResponse response = null;
HttpClient httpclient= null;
httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet();
try {
request.setURI(new URI("IP"));
response = httpclient.execute(request);
}
catch (URISyntaxException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EntityUtils.consumeQuietly(response.getEntity());
InputStream inputStream = null;
String result = "";
try {
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost();
// 4. convert JSONObject to JSON to String
json = jsonArray.toString();
json = json.replace("\\","").replace("\"{" ,"{").replace("}\"" ,"}");
String userName ="admin";
String password = "******";
String base64EncodedCredentials = "Basic " + Base64.encodeToString(
(userName + ":" + password).getBytes(),
Base64.NO_WRAP);
httpPost.setHeader("Authorization", base64EncodedCredentials);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("TenantId", TenantId));
nameValuePairs.add(new BasicNameValuePair("JsonData", json));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpPost.setURI(new URI(UrlPost));
response = httpclient.execute(httpPost);
boolean responseBody = Boolean.parseBoolean(EntityUtils.toString(response.getEntity()));
if ( (response.getStatusLine().getStatusCode()== HttpsURLConnection.HTTP_OK) && responseBody==true ){
Toast.makeText(MainActivity.this, "Updated Data", Toast.LENGTH_SHORT).show();
}
System.out.println(responseBody+" values is");
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
public void enableStrictMode()
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
//for the time schedular functions
private Job createJob() {
int jobType = 3;
boolean isPeriodic = true;
Long miliSecondsInterval = Long.parseLong(Interval)*1000;
intervalInMillisEditText=Long.toString(miliSecondsInterval) ;
String intervalInMillisString = intervalInMillisEditText;
if (TextUtils.isEmpty(intervalInMillisString)) {
return null;
}
Long intervalInMillis = Long.parseLong(intervalInMillisString);
Job.Builder builder = new Job.Builder(JOB_ID, this, jobType, JOB_PERIODIC_TASK_TAG)
.setIntervalMillis(intervalInMillis);
if (isPeriodic) {
builder.setPeriodic(intervalInMillis);
}
return builder.build();
}
private void removePeriodicJob() {
SmartScheduler jobScheduler = SmartScheduler.getInstance(this);
if (!jobScheduler.contains(JOB_ID)) {
Toast.makeText(MainActivity.this, "No job exists with JobID: " + JOB_ID, Toast.LENGTH_SHORT).show();
return;
}
if (jobScheduler.removeJob(JOB_ID)) {
Toast.makeText(MainActivity.this, "Job successfully removed!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onJobScheduled(Context context, final Job job) {
if (job != null) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// System.out.println("Shahbaz is running");
// Toast.makeText(MainActivity.this, "Job: " + job.getJobId() + " scheduled!", Toast.LENGTH_SHORT).show();
CallApi();
getTableData();
}
});
Log.d(TAG, "Job: " + job.getJobId() + " scheduled!");
}
}
//nevigation
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.newItem1) {
Intent intent = new Intent(this,SecondActivity.class);
startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void onResetSchedulerClick(MenuItem item) {
SmartScheduler smartScheduler = SmartScheduler.getInstance(getApplicationContext());
smartScheduler.removeJob(JOB_ID);
Toast.makeText(this, "Service has been Stoped!", Toast.LENGTH_SHORT).show();
// Button btnstart = (Button) findViewById(R.id.button);
// btnstart.setVisibility(View.VISIBLE);
// smartJobButton.setText(getString(R.string.schedule_job_btn));
// smartJobButton.setEnabled(true);
// smartJobButton.setAlpha(1.0f);
}
}
Related
I have some problem about setting and getting id from data that showed with volley JSon array request.
I've tried to do this, but it fail.
ChildTidur.java
public class ChildTidur extends AppCompatActivity implements TidurAdapter.ContactsAdapterListener {
private static final String TAG = ChildTidur.class.getSimpleName();
private RecyclerView recyclerView;
private List<Story> storyList;
private TidurAdapter mAdapter;
private SearchView searchView;
private TextView noFavtsTV;
private AppPreferences appPreferences;
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 2000;
public static final int READ_TIMEOUT = 2000;
final String KEY_SAVED_RADIO_BUTTON_INDEX = "SAVED_RADIO_BUTTON_INDEX";
// url to fetch contacts json
private static final String URL = "https://api.kafeinkode.com/childtidur.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.child_tidur);
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
SwipeRefreshLayout pullToRefresh = findViewById(R.id.pullToRefresh);
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
finish();
startActivity(getIntent());
}
});
//toolbar logo and desc
Toolbar topToolBar = (Toolbar) findViewById(R.id.toolbarTidur);
setSupportActionBar(topToolBar); //munculkan menu ke toolbar
getSupportActionBar().setDisplayHomeAsUpEnabled(true); //this line shows back button
recyclerView = findViewById(R.id.recycler_view);
noFavtsTV = findViewById(R.id.no_favt_text);
storyList = new ArrayList<>();
mAdapter = new TidurAdapter(this, storyList, this, appPreferences);
// white background notification bar
whiteNotificationBar(recyclerView);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new TidurDekor(this, DividerItemDecoration.VERTICAL, 36));
recyclerView.setAdapter(mAdapter);
//Make call to AsyncTask
new AsyncLogin().execute();
//Get radio button value
LoadPreferences();
} //OnCreate
private void showNoFavtText(boolean show) {
noFavtsTV.setVisibility(show ? View.VISIBLE : View.GONE); //jika data yang ditampilkan tidak ada, maka show noFavsTv
recyclerView.setVisibility(show ? View.GONE : View.VISIBLE); //jika data yang ditampilkan tidak ada, maka don't show rV
}
private void LoadPreferences(){
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(R.layout.activity_settings, null,false);
RadioGroup radioGroup = (RadioGroup)contentView.findViewById(R.id.radioSex);
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
int savedRadioIndex = sharedPreferences.getInt(KEY_SAVED_RADIO_BUTTON_INDEX, 0);
RadioButton savedCheckedRadioButton = (RadioButton)radioGroup.getChildAt(savedRadioIndex);
savedCheckedRadioButton.setChecked(true);
RadioGroup genderGroup = (RadioGroup) contentView.findViewById(R.id.radioSex);
RadioButton male = (RadioButton) contentView.findViewById(R.id.theme1);
RadioButton female = (RadioButton) contentView.findViewById(R.id.theme2);
if (genderGroup.getCheckedRadioButtonId() == -1) {
Toolbar tb = (Toolbar) findViewById(R.id.toolbarTidur);
tb.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
}
else {
if (male.isChecked()) { // one of the radio buttons is checked
Toolbar tb1 = (Toolbar) findViewById(R.id.toolbarTidur);
tb1.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
}
else if (female.isChecked()) {
Toolbar tb2 = (Toolbar) findViewById(R.id.toolbarTidur);
tb2.setBackgroundColor(getResources().getColor(R.color.colorAccent));
}
}
}
private class AsyncLogin extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(ChildTidur.this);
HttpURLConnection conn;
java.net.URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
showNoFavtText(false);
pdLoading.setMessage("\tMencoba terhubung ke internet...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL("https://api.kafeinkode.com/childtidur.json");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("koneksi gagal");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
/**
* fetches json by making http calls
*/
protected void onPostExecute(String result) {
JsonArrayRequest request = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
pdLoading.dismiss();
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
List<Story> items = new Gson().fromJson(response.toString(), new TypeToken<List<Story>>() {
}.getType());
// adding contacts to contacts list
storyList.clear();
storyList.addAll(items);
// refreshing recycler view
mAdapter.notifyDataSetChanged();
for (int i=0; i<storyList.size(); i++) {
Story story = new Story();
story.setIdStory(String.valueOf(i));
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pdLoading.dismiss();
// error in getting json
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Tidak bisa menampilkan data. Periksa kembali sambungan internet Anda", Toast.LENGTH_LONG).show();
AlertDialog alertDialog = new AlertDialog.Builder(ChildTidur.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Data Tidak bisa ditampilkan. Periksa kembali sambungan internet Anda");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
showNoFavtText(true);
}
});
TidurSearch.getInstance().addToRequestQueue(request);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_tidur, menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
// Associate searchable_tidur configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search2).getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
// listening to search query text change
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// filter recycler view when query submitted
mAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
// filter recycler view when text is changed
mAdapter.getFilter().filter(query);
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search2) {
return true;
}
//Menu
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
else
if (id == R.id.about_us) {
startActivity(new Intent(this, AboutUs.class));
return true;
}
else
if (id == R.id.favlist) {
startActivity(new Intent(this, ShowFavouriteList.class));
return true;
}
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// close search view on back button pressed
if (!searchView.isIconified()) {
searchView.setIconified(true);
return;
}
super.onBackPressed();
}
private void whiteNotificationBar(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int flags = view.getSystemUiVisibility();
flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
view.setSystemUiVisibility(flags);
getWindow().setStatusBarColor(Color.WHITE);
}
}
#Override
public void onContactSelected(Story story) {
Toast.makeText(getApplicationContext(), "Selected: " + story.getName(), Toast.LENGTH_LONG).show();
}
}
TidurAdapter.java
public void onClick(View view) {
// Another problem lays here when I get id of data
Story story = storyList.get(getLayoutPosition());
int ambilId = Integer.parseInt(story.getIdStory());
if ( 0 == ambilId ) {
Intent myIntent = new Intent(view.getContext(), DoaMauTidur.class);
view.getContext().startActivity(myIntent);
}
else if ( 1 == getAdapterPosition() )
{
Intent myIntent = new Intent(view.getContext(), DoaBangunt.class);
view.getContext().startActivity(myIntent);
}
else if ( 2 == getAdapterPosition() )
{
Intent myIntent = new Intent(view.getContext(), DoaJimak.class);
view.getContext().startActivity(myIntent);
}
}
This is a full code:
Story.java
public Story(){}
String name;
String nomor;
private String idStory;
private int isLiked;
public String getName() {
return name;
}
public String getNomor() { return nomor; }
public void setIdStory(String isStory) {
this.idStory = isStory;
}
public String getIdStory() {
return idStory;
}
public void setIsLiked(int isLiked) {
this.isLiked = isLiked;
}
public int getIsLiked() {
return isLiked;
}
}
ChildTidur.java
/**
* fetches json by making http calls
*/
protected void onPostExecute(String result) {
JsonArrayRequest request = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
pdLoading.dismiss();
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
List<Story> items = new Gson().fromJson(response.toString(), new TypeToken<List<Story>>() {
}.getType());
// adding contacts to contacts list
storyList.clear();
storyList.addAll(items);
// refreshing recycler view
mAdapter.notifyDataSetChanged();
for (int i=0; i<storyList.size(); i++) {
Story story = new Story();
story.setIdStory(String.valueOf(i));
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pdLoading.dismiss();
// error in getting json
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Tidak bisa menampilkan data. Periksa kembali sambungan internet Anda", Toast.LENGTH_LONG).show();
AlertDialog alertDialog = new AlertDialog.Builder(ChildTidur.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Data Tidak bisa ditampilkan. Periksa kembali sambungan internet Anda");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
showNoFavtText(true);
}
});
TidurSearch.getInstance().addToRequestQueue(request);
}
}
TidurAdapter.java
public class TidurAdapter extends RecyclerView.Adapter<TidurAdapter.TidurViewHolder> implements Filterable {
private Context context;
private List<Story> storyList;
private List<Story> storyListFiltered;
private ContactsAdapterListener listener;
private int changedItemPosition;
public boolean isLiked;
private AppPreferences appPreferences;
Boolean checked = false;
public TidurAdapter(Context context, List<Story> storyList, ContactsAdapterListener listener, AppPreferences appPreferences) {
this.context = context;
this.listener = listener;
this.storyList = storyList;
this.storyListFiltered = storyList;
this.appPreferences = appPreferences;
}
#Override
public TidurViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.child_row_item_tidur, parent, false);
return new TidurViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull TidurViewHolder holder, int position) {
final Story story = storyListFiltered.get(position);
holder.name.setText(story.getName());
holder.nomor.setText(story.getNomor());
holder.setViewData(storyList.get(position), holder.getAdapterPosition());
}
#Override
public int getItemCount() {
return storyListFiltered.size();
}
public interface ContactsAdapterListener {
void onContactSelected(Story story);
}
//ViewHolder
public class TidurViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView nomor;
public ImageView mFavorite;
private CheckBox likeCheckBox;
final String KEY_SAVED_RADIO_BUTTON_INDEX = "SAVED_RADIO_BUTTON_INDEX";
public TidurViewHolder(View view) {
super(view);
name = view.findViewById(R.id.name);
nomor = view.findViewById(R.id.nomor);
likeCheckBox = itemView.findViewById(R.id.like_button_cb);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// get id of data
Story story = storyList.get(getLayoutPosition());
int ambilId = Integer.parseInt(story.getIdStory());
if ( 0 == ambilId ) {
Intent myIntent = new Intent(view.getContext(), DoaMauTidur.class);
view.getContext().startActivity(myIntent);
}
else if ( 1 == getAdapterPosition() )
{
Intent myIntent = new Intent(view.getContext(), DoaBangunt.class);
view.getContext().startActivity(myIntent);
}
else if ( 2 == getAdapterPosition() )
{
Intent myIntent = new Intent(view.getContext(), DoaJimak.class);
view.getContext().startActivity(myIntent);
}
}
});
//Get radio button value
LayoutInflater inflater = (LayoutInflater) view.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View cV = inflater.inflate(R.layout.activity_settings, null,false);
RadioGroup radioGroup = (RadioGroup)cV.findViewById(R.id.radioSex);
SharedPreferences sharedPreferences = view.getContext().getSharedPreferences("MY_SHARED_PREF", Activity.MODE_PRIVATE);
int savedRadioIndex = sharedPreferences.getInt(KEY_SAVED_RADIO_BUTTON_INDEX, 0);
RadioButton savedCheckedRadioButton = (RadioButton)radioGroup.getChildAt(savedRadioIndex);
savedCheckedRadioButton.setChecked(true);
RadioGroup genderGroup = (RadioGroup) cV.findViewById(R.id.radioSex);
RadioButton male = (RadioButton) cV.findViewById(R.id.theme1);
RadioButton female = (RadioButton) cV.findViewById(R.id.theme2);
if (genderGroup.getCheckedRadioButtonId() == -1) {
nomor.setBackgroundColor(view.getResources().getColor(R.color.colorPrimaryDark));
} else {
if (male.isChecked()) { // one of the radio buttons is checked
nomor.setBackgroundDrawable(ContextCompat.getDrawable(view.getContext(), R.drawable.rounded_drawable));
}
else if (female.isChecked()) {
nomor.setBackgroundDrawable(ContextCompat.getDrawable(view.getContext(), R.drawable.rounded_drawable_red));
}
}
} //TidurViewHolder(View view)
public void setViewData(final Story story, final int adapterPosition) {
if (story.getIsLiked() == 1) {
likeCheckBox.setChecked(true);
}
else {
likeCheckBox.setChecked(false);
}
likeCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
changedItemPosition = adapterPosition;
if (buttonView.isPressed()) {
if (isChecked) {
isLiked = true;
updateLikes();
appPreferences.saveFavouriteCard(story);
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
}
else {
isLiked = false;
updateLikes();
appPreferences.deleteCard(story.getIdStory());
Toast.makeText(context, "Removed", Toast.LENGTH_SHORT).show();
}
}
}
});
} //setviewdata
public void updateLikes() {
if (isLiked && storyList.get(changedItemPosition).getIsLiked() == 0) { //jika dilakukan like (pada posisi hati kosong) di halaman home
storyList.get(changedItemPosition).setIsLiked(1); //maka jadikan hati berwarna merah di halaman favourite list
notifyItemChanged(changedItemPosition, ACTION_LIKE_IMAGE_CLICKED);
}
else if (!isLiked && storyList.get(changedItemPosition).getIsLiked() == 1) { //jika like dicabut (pada posisi hati yang sedang merah) di halaman home
storyList.get(changedItemPosition).setIsLiked(0); //maka cabut juga warna merah di halaman favourite list
notifyItemChanged(changedItemPosition, ACTION_LIKE_IMAGE_CLICKED);
}
} //updateLikes
}//Class TidurViewHolder
}
The error result is, it is showing null... Which mean no ID that can be obtained.
In your for loop you are not setting id of your List, but your new Story.
Instead of:
for (int i=0; i<storyList.size(); i++) {
Story story = new Story();
story.setIdStory(String.valueOf(i));
}
Use this:
for (int i=0; i<storyList.size(); i++) {
storyList.get(i).setIdStory(String.valueOf(i));
}
Also because your index i=0 starts from zero, you should change for loop index i to start from 1 like this:
for (int i=1; i<=storyList.size(); i++) {
storyList.get(i).setIdStory(String.valueOf(i));
}
Check this main activity:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
private ArrayList<Story> storyList;
// url to fetch contacts json
private static final String URL = "https://api.kafeinkode.com/childtidur.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
storyList = new ArrayList<>();
//Fetch JSON data
fetchData();
}
private void fetchData(){
JsonArrayRequest request = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
List<Story> items = new Gson().fromJson(response.toString(), new TypeToken<List<Story>>() {}.getType());
// adding contacts to contacts list
storyList.clear();
storyList.addAll(items);
for (int i=0; i<storyList.size(); i++) {
storyList.get(i).setIdStory(String.valueOf(i + 1));
}
Log.d("StoryLid: ", storyList.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error in getting json
Log.e(TAG, "Error: " + error.getMessage());
}
});
VolleyService.getInstance(this).getRequestQueue().add(request);
}
}
As a result you have response:
I have SwipeRefreshlayout.I have Implemented for recycler view.I have one problem I did not find solution from 3 days.Please help me for that,Thank you in advance for help me.Below is my activity of swiperefresh ,when I pull down list then swiperefresh progress bsr display but after applying
mSwipeRefreshView.setRefreshing(false);
condition it still show progress please below see my code for that
public class Dashboard extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,
SwipeRefreshLayout.OnRefreshListener {
RecyclerView mRecyclerView;
DashboardAdapter mAdapter;
DashboardGetSet dashboardGetSet;
ArrayList<DashboardGetSet> reportList;
ImageView imgalertIcon;
TextView txtAlertTitle, txtAlertmessage;
Dialog dialog;
Button btnCancel, btnExit;
String alertFlag = "";
String user_id;
ProgressDialog pd;
private static String LOG_TAG = "RecyclerViewActivity";
int id;
public static int totalCount;
SQLiteDatabaseHelper db;
private DrawerLayout drawerLayout;
Toolbar toolbar;
SessionManager sessionManager;
ConnectivityManager connectivityManager;
NetworkInfo networkInfo;
SwipeRefreshLayout mSwipeRefreshView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dmitdashboard);
sessionManager = new SessionManager(getApplicationContext());
init();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()== true) {
loadJSON();
} else {
showCustomDialog1();
}
mSwipeRefreshView.setOnRefreshListener(this);
mSwipeRefreshView.post(new Runnable() {
#Override
public void run() {
mSwipeRefreshView.setRefreshing(true);
loadJSON();
}
}
);
}
private void init() {
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
pd = new ProgressDialog(this);
mAdapter = new DashboardAdapter(reportList);
db = new SQLiteDatabaseHelper(this);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
mSwipeRefreshView = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
mSwipeRefreshView.setColorSchemeResources(R.color.inProcess,
R.color.colorAccent,
R.color.roboto);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mSwipeRefreshView = new SwipeRefreshLayout(this);
}
#Override
protected void onResume() {
super.onResume();
mAdapter.setOnItemClickListener(new DashboardAdapter.MyClickListener(){
#Override
public void onItemClick(int position, View v) {
mSwipeRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.v("Dashboard","SwipeRefresh ");
// Start showing the refresh animation
mSwipeRefreshView.setRefreshing(true);
loadJSON();
Log.v("Dashboard","SwiperefreshLoadJson");
}
});
Log.i(LOG_TAG, " Clicked on Item " + position);
Intent intent =new Intent(Dashboard.this,CustomerDetails.class);
int i = reportList.get(position).getId();
intent.putExtra( "Value",i);
Log.d("Dashboard","Value"+i);
startActivity(intent);
}
});
}
private void loadJSON() {
mSwipeRefreshView.setRefreshing(true);
pd.setTitle("Loading...Please wait!");
pd.show();
Cursor rs = db.getUserId();
if(rs.getCount() > 0)
{
rs.moveToFirst();
do{
id = rs.getInt(rs.getColumnIndex("userid"));
}while(rs.moveToNext());
}
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(Utils.url)
.build();
WebsiteService service = adapter.create(WebsiteService.class);
service.getReports( id,new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
BufferedReader reader = null;
String output = "";
try {
reader = new BufferedReader(new InputStreamReader(response.getBody().in()));
output = reader.readLine();
JSONTokener tokener = new JSONTokener(output);
JSONObject json = new JSONObject(tokener);
String reports="";
JSONArray jsonArray = json.getJSONArray("reports");
reportList = new ArrayList<DashboardGetSet>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
dashboardGetSet = new DashboardGetSet();
id = jsonObj.getInt("id");
Log.d("Login Dashboard", "Id" + id);
dashboardGetSet.setId(id);
String customer_name = jsonObj.getString("customer_name");
dashboardGetSet.setCustomer_name(customer_name);
String father_name = jsonObj.getString("father_name");
dashboardGetSet.setFather_name(father_name);
String mother_name = jsonObj.getString("mother_name");
dashboardGetSet.setMother_name(mother_name);
String date_of_birth = jsonObj.getString("date_of_birth");
dashboardGetSet.setDate_of_birth(date_of_birth);
String gender = jsonObj.getString("gender");
dashboardGetSet.setGender(gender);
String mobile_no = jsonObj.getString("mobile_number");
dashboardGetSet.setMobile_no(mobile_no);
String zone = jsonObj.getString("zone");
dashboardGetSet.setZone(zone);
String address = jsonObj.getString("address");
dashboardGetSet.setAddress(address);
String zip = jsonObj.getString("zip");
dashboardGetSet.setZip(zip);
String city = jsonObj.getString("city");
dashboardGetSet.setCity(city);
String state = jsonObj.getString("state");
dashboardGetSet.setState(state);
String occuption = jsonObj.getString("occupation");
dashboardGetSet.setOccuption(occuption);
user_id = jsonObj.getString("current_user_id");
dashboardGetSet.setUser_id(user_id);
String status = jsonObj.getString("status");
dashboardGetSet.setStatus(status);
String report_status = jsonObj.getString("report_status");
dashboardGetSet.setReport_status(report_status);
String file_name = jsonObj.getString("file_name");
dashboardGetSet.setFile_name(file_name);
String saved_file_name = jsonObj.getString("saved_file_name");
dashboardGetSet.setSaved_file_name(saved_file_name);
String soft_copy_file_name = jsonObj.getString("soft_copy_file_name");
dashboardGetSet.setSaved_file_name(soft_copy_file_name);
String soft_copy_saved_file_name = jsonObj.getString("soft_copy_saved_file_name");
dashboardGetSet.setSoft_copy_saved_file_name(soft_copy_saved_file_name);
String created_at = jsonObj.getString("created_at");
dashboardGetSet.setCreated_at(created_at);
String updated_at = jsonObj.getString("updated_at");
dashboardGetSet.setUpdated_at(updated_at);
String payment_type = jsonObj.getString("payment_type");
dashboardGetSet.setPayment_type(payment_type);
String amount = jsonObj.getString("amount");
dashboardGetSet.setAmount(amount);
String counsellor_id = jsonObj.getString("counsellor_id");
dashboardGetSet.setCounsellor_id("counsellor_id");
db.insertUserDetails(id,customer_name, father_name, mother_name, date_of_birth, gender, mobile_no, counsellor_id, zone, address, zip, city, state, occuption, user_id, status, report_status, created_at, updated_at, payment_type, amount);
reportList.add(dashboardGetSet);
}
mAdapter = new DashboardAdapter(getApplication(), reportList);
mRecyclerView.setAdapter(mAdapter);
getCount();
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void failure(RetrofitError error) {
pd.dismiss();
mSwipeRefreshView.setRefreshing(false);
Toast.makeText(Dashboard.this, error.toString(), Toast.LENGTH_LONG).show();
}
});
}
private void getCount() {
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(Utils.url)
.build();
RestInterface service = adapter.create(RestInterface.class);
service.getCounts(user_id, new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
BufferedReader reader = null;
String output = "";
try {
reader = new BufferedReader(new InputStreamReader(response.getBody().in()));
output = reader.readLine();
JSONTokener tokener = new JSONTokener(output);
JSONObject json = new JSONObject(tokener);
String reports="";
int total = json.getInt("total");
Log.d("Login Dashboard", "total" + total);
dashboardGetSet = new DashboardGetSet();
dashboardGetSet.setCustomerCount(total);
totalCount = dashboardGetSet.getCustomerCount();
TextView mtotalCount = (TextView)findViewById(R.id.countText);
mtotalCount.setText("Total Reports = "+totalCount);
Log.d("Dashboard","Total Counts"+totalCount);
pd.dismiss();
if(mSwipeRefreshView.isRefreshing()){
mSwipeRefreshView.setRefreshing(false);
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void failure(RetrofitError error) {
pd.dismiss();
mSwipeRefreshView.setRefreshing(false);
Toast.makeText(Dashboard.this, error.toString(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(1,R.id.logout,1,"Logout");
item.setIcon(R.drawable.logout);
MenuItemCompat.setShowAsAction(item,MenuItem.SHOW_AS_ACTION_ALWAYS);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.logout:
alertFlag = "Logout";
showCustomDialog();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
protected void showCustomDialog() {
dialog = new Dialog(Dashboard.this,
android.R.style.Theme_Translucent);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
Window window = dialog.getWindow();
window.setLayout(RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT);
window.setGravity(Gravity.CENTER);
dialog.setCancelable(true);
dialog.setContentView(R.layout.custom_dialog);
txtAlertTitle = (TextView) dialog.findViewById(R.id.textView1);
txtAlertmessage = (TextView) dialog.findViewById(R.id.txtmessage);
btnCancel = (Button) dialog.findViewById(R.id.btnCancel);
btnExit = (Button) dialog.findViewById(R.id.btnExit);
btnExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sessionManager.logoutUser();
db.deleteUser( LogInActivity.id);
Intent intent = new Intent(Dashboard.this,
LogInActivity.class);
startActivity(intent);
finish();
}
});
btnCancel.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
if(alertFlag.equals("Logout"))
{
String uri = "#android:drawable/ic_menu_help";
txtAlertTitle.setText("Logout");
txtAlertmessage.setText("Do you want to Logout ?");
btnExit.setText("Ok");
btnCancel.setText("Cancel");
btnExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Dashboard.this,
LogInActivity.class);
startActivity(intent);
finish();
}
});
}else if(alertFlag.equals("Back")){
String uri = "#android:drawable/ic_dialog_info";
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
Drawable res = getResources().getDrawable(imageResource);
imgalertIcon.setImageDrawable(res);
txtAlertTitle.setText("Exit");
txtAlertmessage.setText("Do you want to Exit ?");
btnExit.setText("Ok");
btnCancel.setText("Cancel");
}
dialog.show();
}
protected void showCustomDialog1() {
dialog = new Dialog(Dashboard.this,
android.R.style.Theme_Translucent);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
Window window = dialog.getWindow();
window.setLayout(RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT);
window.setGravity(Gravity.CENTER);
dialog.setCancelable(true);
dialog.setContentView(R.layout.custom_dialog);
txtAlertTitle = (TextView) dialog.findViewById(R.id.textView1);
txtAlertmessage = (TextView) dialog.findViewById(R.id.txtmessage);
btnCancel = (Button) dialog.findViewById(R.id.btnCancel);
btnExit = (Button) dialog.findViewById(R.id.btnExit);
btnCancel.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
String uri = "#android:drawable/ic_menu_help";
txtAlertTitle.setText("Setting");
txtAlertmessage.setText("Network Not Available Do You Want To Go Network Setting ?");
btnExit.setText("OK");
btnCancel.setText("Cancel");
btnExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Settings.ACTION_SETTINGS);
startActivity(intent);
finish();
}
});
dialog.show();
}
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id) {
case R.id.home:
Toast.makeText(getApplicationContext(), "Home", Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawers();
break;
case R.id.changePassword:
Intent intent =new Intent(Dashboard.this,ChangePasswordActivity.class);
startActivity(intent);
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onRefresh() {
loadJSON();
}
}
Hello guys i have an issue with my search activit. If i try to search an item for example (iphone 6) and type only "iphone" or "6" or only "i" and other exc... the search works god, but if i put the entire name of the item in this case : iphone 6 , apps crash.
This is the code :
public class SearchActivity extends AppCompatActivity {
Toolbar toolbar;
ListView lsv;
String categoryId,keyword,city;
ProgressDialog progressBar;
List<CatAdd> catAddList;
CateAdDisplayAdapter adapter;
Typeface typeface;
#SuppressLint("NewApi") #Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activty_search);
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
toolbar.setTitle("Browse Ads");
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
getActionBarTextView();
typeface = Typeface.createFromAsset(getAssets(), "fonts/GandhiSerif-Bold.otf");
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
lsv = (ListView)findViewById(R.id.listView1);
catAddList = new ArrayList<CatAdd>();
categoryId = getIntent().getExtras().getString("categoryId", "0");
keyword = getIntent().getExtras().getString("keyword","keyword");
city = getIntent().getExtras().getString("city","city");
new SearchList().execute();
lsv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent intent = new Intent(getApplicationContext(), BrowseAdsDetailActivity.class);
intent.putExtra("adId", String.valueOf(catAddList.get(arg2).getAddid()));
startActivity(intent);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if(id==android.R.id.home)
{
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
private TextView getActionBarTextView() {
TextView titleTextView = null;
try {
Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
titleTextView = (TextView)f.get(toolbar);
titleTextView.setTypeface(typeface);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
return titleTextView;
}
class SearchList extends AsyncTask<Void, Void, Void>
{
String jsonStr = null;
CustomProgressDialog cd = new CustomProgressDialog();
#Override
protected void onPreExecute() {
super.onPreExecute();
cd.showdialog(SearchActivity.this, "Loading...");
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
jsonStr = sh.makeServiceCall(String.format(Constants.ADSEARCH_URL,categoryId,city,keyword), ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray contacts = jsonObj.getJSONArray(Constants.TAG);
for (int i = contacts.length()-1; i > -1; i--) {
JSONObject c = contacts.getJSONObject(i);
String adId = c.getString(Constants.CAT_ADID);
String adTitle = c.getString(Constants.CAT_ADTITLE);
String adDes = c.getString(Constants.CAT_ADDES);
String adCreatedAt = c.getString("adCreatedAt");
String adcity= c.getString(Constants.CAT_CITY);
String adPrise= c.getString(Constants.CAT_PRICE);
JSONArray arrImages=c.getJSONArray("images");
ArrayList<String> imgArray=new ArrayList<String>();
for(int j=0;j<arrImages.length();j++)
{
JSONObject imgObj=arrImages.getJSONObject(j);
if(imgObj.has("imageName"))
{
imgArray.add(imgObj.getString("imageName"));
}
}
CatAdd v=new CatAdd();
v.setAddid(Integer.parseInt(adId));
v.setAdTitle(adTitle);
v.setAdDesc(adDes);
v.setAdCreatedAt(adCreatedAt);
v.setAdPrice(adPrise);
v.setImglist(imgArray);
v.setAdCity(adcity);
catAddList.add(v);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
cd.dismissdialog();
adapter = new CateAdDisplayAdapter(getApplicationContext(), catAddList);
lsv.setAdapter(adapter);
}
}
Assuming you are making an api call:
You should encode parameters in your url.
String query = URLEncoder.encode("phone 6", "utf-8");
String url = "http://myurl.com/search?q=" + query;
The result would be: http://myurl.com/search?q=phone%206
I am working on an instant chat application.My problem is that when i am sending message through my chat application,Message is displayed two times instead of one.Screen shot is given below :
As you can see in the acreenshot that the message hiii is displayed two times but i have sent only once.
1.Adapter_Message.java
public class Adapter_Message extends BaseAdapter {
private Context context;
private List<Bean_Message> messagesItems;
public Adapter_Message(Context context, List<Bean_Message> navDrawerItems) {
this.context = context;
this.messagesItems = navDrawerItems;
}
#Override
public int getCount() {
return messagesItems.size();
}
#Override
public Object getItem(int position) {
return messagesItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Bean_Message m = messagesItems.get(position);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// Identifying the message owner
if (messagesItems.get(position).isSelf()) {
// message belongs to you, so load the right aligned layout
convertView = mInflater.inflate(R.layout.list_item_message_right, null);
} else {
// message belongs to other person, load the left aligned layout
convertView = mInflater.inflate(R.layout.list_item_message_left, null);
}
TextView lblFrom = (TextView) convertView.findViewById(R.id.lblMsgFrom);
TextView txtMsg = (TextView) convertView.findViewById(R.id.txtMsg);
txtMsg.setText(m.getMessage());
lblFrom.setText(m.getFromName());
return convertView;
}
}
2.Chat_Activity.java
public class ChatActivity extends FragmentActivity implements
EmojiconGridFragment.OnEmojiconClickedListener, EmojiconsFragment.OnEmojiconBackspaceClickedListener {
public static final String TAG = ChatActivity.class.getSimpleName();
// EditText edMessage;
EmojiconEditText edMessage;
Button sendMessage;
private Socket mSocket;
String sID, lID, md5StringRoomID, message, friendName, loggedInUser;
String frndID;
int smallerID, largerID;
//AlmaChatDatabase almaChatDatabase;
// Chat messages list adapter
private Adapter_Message adapter;
private List<Bean_Message> listBeanMessages;
private ListView listViewMessages;
boolean isSelf; // to check whether the message is owned by you or not.true means message is owned by you .
Bean_Message msg;
int loggedInUserID;
private String URL_FEED_Message = "";
APIConfiguration apiConfiguration;
SharedPreferences preferences;
HashMap<String, Integer> emoticons;
// instance initialization block
{
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
Log.e("Socket", String.valueOf(mSocket));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
sendMessage = (Button) findViewById(R.id.btnSendMessage);
preferences = getApplicationContext().getSharedPreferences(Prefs_Registration.prefsName, Context.MODE_PRIVATE);
//Handling emoticons
/* emoticons = new HashMap<String,Integer>();
emoticons.put(":-)",R.drawable.s1);*/
String id = preferences.getString(Prefs_Registration.get_user_id, null);
// Converting String id to integer
loggedInUserID = Integer.parseInt(id);
//loggedInUserID = almaChatDatabase.getUserID(); // Getting ID of the Logged in user from the database
Log.e("UserID", "Id of Logged in user " + loggedInUserID);
listBeanMessages = new ArrayList<Bean_Message>();
adapter = new Adapter_Message(getApplicationContext(), listBeanMessages);
listViewMessages = (ListView) findViewById(R.id.list_view_messages);
listViewMessages.setAdapter(adapter);
// Getting the ID of the friend from the previous screen using getExtras
Bundle bundle = getIntent().getExtras();
frndID = bundle.getString("ID");
Log.e("FriendID", frndID);
final int friendID = Integer.parseInt(frndID);
friendName = bundle.getString("name");
Log.e("FriendName", friendName);
loggedInUser = preferences.getString(Prefs_Registration.get_user_name, null);
//loggedInUser = almaChatDatabase.getUserName(); // Name of logged in user
Log.e("LoggedInUser", loggedInUser);
// Converting first lowercase letter of every word in Uppercase
final String loggedInUpper = upperCase(loggedInUser);
//To find the current time
Date d = new Date();
final long time = d.getTime();
// Comparing the loggedInUserId and friendID
if (friendID < loggedInUserID) {
smallerID = friendID;
largerID = loggedInUserID;
} else {
smallerID = loggedInUserID;
largerID = friendID;
}
sID = String.valueOf(smallerID);
lID = String.valueOf(largerID);
String combinedID = sID + lID;
Log.e("combined ID", combinedID);
md5StringRoomID = convertPassMd5(combinedID); // Encrypting the combinedID to generate Room ID
Log.e("md5StringRoomID", md5StringRoomID);
// Using the API for loading old chat messages
apiConfiguration = new APIConfiguration();
String api_message = apiConfiguration.getApi_message(); // Getting the API of messages
URL_FEED_Message = api_message + md5StringRoomID; // md5String is the encrypted room ID here
Log.e("URL_FEED_MESSAGE", URL_FEED_Message);
Log.e("Network request", "Fresh Request");
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(URL_FEED_Message);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONArray(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL_FEED_Message, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.e("JsonArray", String.valueOf(jsonArray));
if (jsonArray != null) {
parseJsonFeed(jsonArray);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("ErrorResponse", String.valueOf(volleyError));
}
}
);
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
}
edMessage = (EmojiconEditText) findViewById(R.id.edtMessage);
//Listening on Events
mSocket.on(Socket.EVENT_CONNECT, onConnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectionError);
mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.on("send:notice", onReceive); // Listening event for receiving messages
mSocket.connect(); // Explicitly call connect method to establish connection here
mSocket.emit("subscribe", md5StringRoomID);
sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = edMessage.getText().toString().trim();
Log.e("Sending", "Sending data-----" + message);
if (!message.equals("")) {
edMessage.setText(" ");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("room_id", md5StringRoomID);
jsonObject.put("user", loggedInUpper);
jsonObject.put("id", friendID);
jsonObject.put("message", message);
jsonObject.put("date", time);
jsonObject.put("status", "sent");
} catch (JSONException e) {
e.printStackTrace();
}
isSelf = true; // Boolean isSelf is set to be true as sender of the message is logged in user i.e. you
attemptToSend(loggedInUpper, message, isSelf);
mSocket.emit("send", jsonObject); // owner i.e LoggedIn user is sending the message
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Please enter some text", Toast.LENGTH_LONG).show();
}
});
}
}
});
setEmojiconFragment(false);
}
/* public Spannable getSmiledText(String text) {
SpannableStringBuilder builder = new SpannableStringBuilder(text);
if (emoticons.size() > 0) {
int index;
for (index = 0; index < builder.length(); index++) {
if (Character.toString(builder.charAt(index)).equals(":")) {
for (Map.Entry<String, Integer> entry : emoticons.entrySet()) {
int length = entry.getKey().length();
if (index + length > builder.length())
continue;
if (builder.subSequence(index, index + length).toString().equals(entry.getKey())) {
builder.setSpan(new ImageSpan(getApplicationContext(), entry.getValue()), index, index + length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
index += length - 1;
break;
}
}
}
}
}
return builder;
}*/
private void setEmojiconFragment(boolean useSystemDefault) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.emojicons, EmojiconsFragment.newInstance(useSystemDefault))
.commit();
}
//Adding message in the arrayList
public void attemptToSend(String senderName, String message, boolean isSelf) {
msg = new Bean_Message(senderName, message, isSelf);
listBeanMessages.add(msg);
adapter.notifyDataSetChanged();
playBeep();
}
// Playing sound when the message is sent by the owner
public void playBeep() {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
// encrypting string into MD5
public static String convertPassMd5(String pass) {
String password = null;
MessageDigest mdEnc;
try {
mdEnc = MessageDigest.getInstance("MD5");
mdEnc.update(pass.getBytes(), 0, pass.length());
pass = new BigInteger(1, mdEnc.digest()).toString(16);
while (pass.length() < 32) {
pass = "0" + pass;
}
password = pass;
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
return password;
}
// Converting first lowercase letter of every word in Uppercase
String upperCase(String source) {
StringBuffer res = new StringBuffer();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
return res.toString().trim();
}
// Event Listeners
private Emitter.Listener onConnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Socket", "Connected");
}
};
private Emitter.Listener onConnectionError = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Error", "Error in connecting server");
}
};
private Emitter.Listener onDisconnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Disconnect", "Socket Disconnected");
}
};
// Event Listener for receiving messages
private Emitter.Listener onReceive = new Emitter.Listener() {
#Override
public void call(final Object... args) {
Log.e("Receive", "Bean_Message received");
runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
Log.e("DATA", String.valueOf(data));
try {
JSONArray ops = data.getJSONArray("ops");
for (int i = 0; i < ops.length(); i++) {
JSONObject object = ops.getJSONObject(i);
String roomID = object.getString("room_id");
Log.e("RoomID", roomID); // Getting room ID from JSON array
Log.e("Md5RoomID", md5StringRoomID); // Getting room id which we have created using logged in user ID and room id of the user through which chat has to be done
//Comparing the room IDs
if (md5StringRoomID.equals(roomID)) {
String senderName = object.getString("user");
Log.e("Sender Name", senderName);
String senderID = object.getString("id");
Log.e("SenderID", senderID);
// JSONObject message = object.getJSONObject("message");
String messageReceived = object.getString("message");
Log.e("Bean_Message Received", messageReceived);
String loggedInUSerNAme = preferences.getString(Prefs_Registration.get_user_name, null);
//String loggedInUSerNAme = almaChatDatabase.getUserName();
//If the message is sent by the owner to other from webapp ,then we need to check whether the sender is the loggedinUSer in the App or not and we will right align the messages .
if (loggedInUSerNAme.equalsIgnoreCase(senderName)) {
isSelf = true;
msg = new Bean_Message(senderName, messageReceived, isSelf);
listBeanMessages.add(msg);
// Log.e("List Elements", String.valueOf(listBeanMessages));
adapter.notifyDataSetChanged();
playBeep();
} else {
isSelf = false;
msg = new Bean_Message(senderName, messageReceived, isSelf);
listBeanMessages.add(msg);
Log.e("List Elements", String.valueOf(listBeanMessages));
adapter.notifyDataSetChanged();
playBeep();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
// Playing sound when the message is sent by other
public void playBeep() {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
};
// Parsing JSon Array which corresponds to the old chat messages
public void parseJsonFeed(JSONArray jsonArray) {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String roomID = jsonObject.getString("room_id");
Log.e("RoomID", roomID);
Log.e("Md5RoomID", md5StringRoomID);
// If Room ID(created using id of logged in user and id of friend) matches with the room id obtained from JSON String
if (md5StringRoomID.equals(roomID)) {
String userName = jsonObject.getString("user");
Log.e("Name", userName);
String loggedInUSerNAme = preferences.getString(Prefs_Registration.get_user_name, null);
//String loggedInUSerNAme = almaChatDatabase.getUserName();
Log.e("LoggedInUSer", loggedInUSerNAme);
//If the message is sent by the owner to other from webapp ,then we need to check whether the sender is the loggedinUSer in the App or not and we will right align the messages .
if (loggedInUSerNAme.equalsIgnoreCase(userName)) {
String message = jsonObject.getString("message");
Log.e("message", message);
isSelf = true;
msg = new Bean_Message(userName, message, isSelf);
listBeanMessages.add(msg);
adapter.notifyDataSetChanged();
//playBeep();
} else {
JSONObject jsonMessage = jsonObject.getJSONObject("message");
String message = jsonMessage.getString("text");
isSelf = false;
msg = new Bean_Message(userName, message, isSelf);
listBeanMessages.add(msg);
adapter.notifyDataSetChanged();
// playBeep();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// notify data changes to list adapter
//adapter.notifyDataSetChanged();
}
}
#Override
public void onEmojiconBackspaceClicked(View view) {
EmojiconsFragment.backspace(edMessage);
}
#Override
public void onEmojiconClicked(Emojicon emojicon) {
EmojiconsFragment.input(edMessage, emojicon);
}
}
3.Bean_Message.java
public class Bean_Message {
private String fromName, message;
private boolean isSelf; // isSelf is used to check whether the message is owned by you or not
public Bean_Message() {
}
public Bean_Message(String fromName, String message, boolean isSelf) {
this.fromName = fromName;
this.message = message;
this.isSelf = isSelf;
}
public String getFromName() {
return fromName;
}
public void setFromName(String fromName) {
this.fromName = fromName;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isSelf() {
return isSelf;
}
public void setSelf(boolean isSelf) {
this.isSelf = isSelf;
}
}
On clicking "Send Message" button ,message is sent to he server and the following code is used:
public void attemptToSend(String senderName, String message, boolean isSelf) {
msg = new Bean_Message(senderName, message, isSelf);
listBeanMessages.add(msg);
adapter.notifyDataSetChanged();
playBeep();
}
Message is stored in the Bean and Bean is added in the ArrayList .Now i am notifying my adapter that the ArrayList is updated using adapter.notifyDataSetChanged() method.But the problem is List view is displaying my sent message two times.Please help me to solve the issue .
I am currently working on an Android app. It has a navigation drawer and a few fragments. I want the actionbar title to change depending on the fragment. I have managed to do this. But the problem is when I press the back button the setTitle() method is executed and the title is changed but it does not reflect on the action bar visibly.
EDIT: I found out that the problem was with the navigation drawer opening and closing. So I removed the changing title part from the ondraweropened() and ondrawerclosed(). It solved the current problem. But I want the name to change on opening and retain the current fragment name on closing. Can anyone help me on that?
This is my main activity:
public class HomeActivity extends ActionBarActivity {
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
static final String DISPLAY_MESSAGE_ACTION="com.example.test.DISPLAY_MESSAGE";;
static final String SERVER_URL = "http://doylefermi.x20.in/register.php";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static String acc = "";
public String msg = "";
public static String accn = "";
String SENDER_ID = "1019787135827";
static final String TAG = "GCMDemo";
TextView mDisplay;
GoogleCloudMessaging gcm;
AtomicInteger msgId = new AtomicInteger();
SharedPreferences prefs;
Context context;
String regid="";
String email="";
String title="";
String name="";
private DrawerLayout mDrawerLayout;
private android.support.v4.app.ActionBarDrawerToggle mDrawerToggle;
private String[] navMenuTitles;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader= new ArrayList<String>();
HashMap<String, List<String>> listDataChild=new HashMap<String,List<String>>();
private LinearLayout mDrawerLinear;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
setupActionBar();
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction transaction;
transaction=fragmentManager.beginTransaction();
Fragment f=new DestinationsFragment();
transaction.replace(R.id.frame_layout, f).commit();
mDrawerLinear= (LinearLayout) findViewById(R.id.left_drawer);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
mDrawerLayout = (DrawerLayout) findViewById(R.id.nav_bar);
mDrawerLinear = (LinearLayout) findViewById(R.id.left_drawer);
expListView = (ExpandableListView) findViewById(R.id.tourist_list);
gcmcheck();
listDataHeader.add(navMenuTitles[0]);
listDataHeader.add(navMenuTitles[1]);
listDataHeader.add(navMenuTitles[2]);
listDataHeader.add(navMenuTitles[3]);
listDataHeader.add(navMenuTitles[4]);
List<String> dest=new ArrayList<String>();
List<String> attr=new ArrayList<String>();
List<String> spl=new ArrayList<String>();
List<String> fest=new ArrayList<String>();
List<String> abtus=new ArrayList<String>();
attr.add("Water World");
attr.add("Temples");
attr.add("Arts & Crafts");
listDataChild.put(listDataHeader.get(0), dest); // Header, Child data
listDataChild.put(listDataHeader.get(1), attr);
listDataChild.put(listDataHeader.get(2), spl);
listDataChild.put(listDataHeader.get(3), fest); // Header, Child data
listDataChild.put(listDataHeader.get(4), abtus);
mDrawerLayout = (DrawerLayout) findViewById(R.id.nav_bar);
mDrawerToggle = new android.support.v4.app.ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
invalidateOptionsMenu();
super.onDrawerClosed(view);
getSupportActionBar().setTitle(title);
}
public void onDrawerOpened(View drawerView) {
title=getTitle().toString();
invalidateOptionsMenu();
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(R.string.action_bar_title1);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
listAdapter=new ExpandableListAdapter(this,listDataHeader,listDataChild);
expListView.setAdapter(listAdapter);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
expListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener(){
#Override
public boolean onGroupClick(ExpandableListView parent,View v,int groupPosition,long id){
if(groupPosition!=1)
{
displayView(groupPosition,groupPosition);
return false;
}
else
return false;
}
});
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
displayView(groupPosition,childPosition);
return false;
}
});
}
private void displayView(int group,int position ) {
Fragment fragment = null;
switch (group) {
case 0: fragment=new DestinationsFragment();title="Destinations";break;
case 1: switch(position){
case 0:fragment=new WaterWorldFragment();title="Water World";break;
case 1:fragment=new TemplesFragment();title="Temples";break;
case 2:fragment=new ArtsCraftsFragment();title="Arts & Crafts";break;
}
break;
case 2: fragment=new SpecialInterestFragment();title="Special Interest";
break;
case 3: fragment=new FestivalsFragment();title="Festivals";
break;
case 4: fragment=new AboutUsFragment();title="About Us";
break;
default: break;
}
if (fragment != null) {
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction transaction;
transaction=fragmentManager.beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.frame_layout, fragment).commit();
expListView.setItemChecked(position, true);
expListView.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerLinear);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void onBackPressed(){
if(mDrawerLayout.isDrawerOpen(Gravity.LEFT))
{
mDrawerLayout.closeDrawer(Gravity.LEFT);
}
else{
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater m=getMenuInflater();
m.inflate(R.menu.menu_home,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu (Menu menu){
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerLinear);
return super.onPrepareOptionsMenu(menu);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
public void setupActionBar(){
//getSupportActionBar().setTitle(R.string.app_name);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(0xffff5253));
}
private void gcmcheck()
{
Account[] accounts = AccountManager.get(this).getAccounts();
acc= accounts[1].name;
accn=acc.substring(0, acc.indexOf('#'));
name=accn;
email=acc;
context = getApplicationContext();
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (regid=="") { //Toast.makeText(getApplicationContext(), "Registering device...", Toast.LENGTH_SHORT).show();
registerInBackground();
}
//else {Toast.makeText(getApplicationContext(), "Device registered, registration ID=" + regid,Toast.LENGTH_LONG).show(); }
}
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; setContentView(R.layout.activity_main);if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
return registrationId;
}
private SharedPreferences getGCMPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
// how you store the regID in your app is up to you.
return getSharedPreferences(HomeActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}
private void registerInBackground() {
new AsyncTask<Void,Void,String>() {
#Override
protected String doInBackground(Void... params) {
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
// You should send the registration ID to your server over HTTP,
// so it can use GCM/HTTP or CCS to send messages to your app.
// The request to your server should be authenticated if your app
// is using accounts.
sendRegistrationIdToBackend();
// For this demo: we don't need to send it because the device
// will send upstream messages to a server that echo back the
// message using the 'from' address in the message.
// Persist the regID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
}
private void sendRegistrationIdToBackend() {
final int MAX_ATTEMPTS = 5;
final int BACKOFF_MILLI_SECONDS = 2000;
final Random random = new Random();
Log.i(TAG, "registering device (regId = " + regid + ")");
String serverUrl = SERVER_URL;
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regid);
params.put("name",name);
params.put("email",email);
long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
// Once GCM returns a registration id, we need to register on our server
// As the server might be down, we will retry it a couple
// times.
for (int i = 1; i <= MAX_ATTEMPTS; i++) {
Log.d(TAG, "Attempt #" + i + " to register");
try {
post(serverUrl, params);
// displayMessage(context, "Registered");
return;
} catch (IOException e) {
// Here we are simplifying and retrying on any error; in a real
// application, it should retry only on unrecoverable errors
// (like HTTP error code 503).
Log.e(TAG, "Failed to register on attempt " + i + ":" + e);
if (i == MAX_ATTEMPTS) {
break;
}
try {
Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
Thread.sleep(backoff);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
Log.d(TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return;
}
// increase backoff exponentially
backoff *= 2;
}
}
// String message = context.getString(R.string.server_register_error,
// MAX_ATTEMPTS);
//CommonUtilities.displayMessage(context, message);
}
private void post(String endpoint, Map<String, String> params)throws IOException{
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Map.Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.v(TAG, "Posting '" + body+ "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
Log.e("URL", "> " + url);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
protected void onPostExecute(String msg) {
//setContentView(R.layout.activity_gcm_broadcast_receiver);
}
}.execute(null, null, null);}
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
//int appVersion = getAppVersion(context);
// Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
// editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
}
This is one of the fragments:-
public class DestinationsFragment extends Fragment {
ViewPager viewPager;
public class DestinationsFragment extends Fragment implements View.OnClickListener {
private TypedArray Icons;
PagerAdapter adapter;
String[] rank;
String[] country;
String[] population;
int[] flag;
public DestinationsFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_5, container, false);
Icons= getResources().obtainTypedArray(R.array.nav_drawer_icons);
View rootView = inflater.inflate(R.layout.activity_5, container, false);
Button button1;
rank = new String[] { "Heading1", "Heading2", "Heading3", "Heading4", "Heading5", "Heading6", "Heading7", "Heading8", "Heading9", "Heading10" };
country = new String[] { "Text1", "Text2", "Text3",
"Text4", "Text5", "Text6", "Text7", "Text8",
"Text9", "Text10" };
population = new String[] { "Subtext1", "Subtext2",
"Subtext3", "Subtext4", "Subtext5", "Subtext6",
"Subtext7", "Subtext8", "Subtext9", "Subtext10" };
flag = new int[] { R.mipmap.ic_launcher, R.mipmap.ic_launcher,
R.mipmap.ic_launcher, R.mipmap.ic_launcher,
R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,
R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher };
// Locate the ViewPager in viewpager_main.xml
//viewPager = (ViewPager) findViewById(R.id.pager);
// Pass results to ViewPagerAdapter Class
//adapter = new ViewPagerAdapter(DestinationsFragment.this, rank, country, population, flag);
//adapter = new ViewPagerAdapter(getChildFragmentManager());
viewPager = (ViewPager) rootView.findViewById(R.id.pager);
// Binds the Adapter to the ViewPager
viewPager.setAdapter(buildAdapter());
return rootView;
}
#Override
public void onResume(){
super.onResume();
getActivity().setTitle(R.string.dest);
}
private PagerAdapter buildAdapter() {
return(new ViewPagerAdapter(getActivity().getApplicationContext(), rank, country, population, flag));
}
population = new String[] { "Subtext1", "Subtext2",
"Subtext3", "Subtext4", "Subtext5", "Subtext6",
"Subtext7", "Subtext8", "Subtext9", "Subtext10" };
flag = new int[] { R.mipmap.ic_launcher, R.mipmap.ic_launcher,
R.mipmap.ic_launcher, R.mipmap.ic_launcher,
R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,
R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher };
ViewPager viewPager = (ViewPager) rootView.findViewById(R.id.pager);
viewPager.setClipToPadding(false);
viewPager.setPageMargin(-100);
// Binds the Adapter to the ViewPager
viewPager.setAdapter(buildAdapter());
button1 = (Button) rootView.findViewById(R.id.button1);
button1.setOnClickListener(this);
return rootView;
}
private PagerAdapter buildAdapter() {
return(new ViewPagerAdapter(getActivity().getApplicationContext(), rank, country, population, flag));
}
#Override
public void onClick(View v) {
Toast.makeText(getActivity().getApplicationContext(), "OK", Toast.LENGTH_LONG).show();
}
}
Try this !.
//on home activity
public ActionBar getsupportactionbar() {
ActionBar mActionBar = getSupportActionBar();
return mActionBar;
}
On your fragments :
ActionBar mActionBar = ((HomeActivity) getActivity()).getsupportactionbar();
if(mActionBar !=null)
mActionBar .setTitle(R.string.dest);
or may be you need to settitle on OnactivityCreated.