refresh current page without blinking android - android

My app has a list and a button to add element to the list and reload it in the same activity, when pressing the button I need to reload the activity without blinking or time of reloading Like when you send message in messenger.I try the following code:
recreate()
tvSender.setText("");
And this code :
Intent intent = getIntent();
finish();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
This works but it's still not what i want exact any help pls
the full code :
public class ChatRoom extends AppCompatActivity {
String username;
String username1;
TextView userroom;
String image1;
Message_adapter adapter;
ListView L_MESSAGES;
ArrayList<Messages> messages= new ArrayList<Messages>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
Intent intent = getIntent();
username = intent.getStringExtra("username");
username1 = intent.getStringExtra("username1");
userroom =(TextView) findViewById(R.id.userroom);
final EditText tvSender =(EditText) findViewById(R.id.Sender);
final ImageButton btSender=(ImageButton)findViewById(R.id.btSender);
final ImageButton btBack=(ImageButton)findViewById(R.id.back);
btBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChatRoom.this, ChatActivity.class);
intent.putExtra("username", username);
intent.putExtra("username1", username1);
ChatRoom.this.startActivity(intent);
}
});
btSender.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String message=tvSender.getText().toString();
Response.Listener<String> responselistener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if (success) {
recreate();
tvSender.setText("");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
MessageSender loginrequest = new MessageSender(message, username,username1, responselistener);
RequestQueue queue = Volley.newRequestQueue(ChatRoom.this);
queue.add(loginrequest);
}
});
getsendMessages();
}
private void getsendMessages(){
String url =config_message.DATA_URL1+username+"&username1="+username1;
userroom.setText(username1);
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJsonFriend(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(ChatRoom.this,volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJsonFriend(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(config_message.JSON_ARRAY);
JSONObject collegeData =null;
messages.clear();
for(int i=0;i<result.length();i++) {
collegeData = result.getJSONObject(i);
String friend = collegeData.getString(config_message.KEY_SENDER);
image1 = collegeData.getString(config_message.KEY_IMAGE);
String time = collegeData.getString(config_message.KEY_Time);
String sender = collegeData.getString(config_message.KEY_Sender);
messages.add(new Messages(friend,image1,time,sender));
}
} catch (JSONException e) {
e.printStackTrace();
}
L_MESSAGES=(ListView) findViewById(R.id.chatRoomsList);
adapter = new Message_adapter(this,messages);
L_MESSAGES.setAdapter(adapter);
L_MESSAGES.setSelection(L_MESSAGES.getAdapter().getCount()-1);
}
}
this the button to refresh list:
public void onClick(View v) {
final String message=tvSender.getText().toString();
Response.Listener<String> responselistener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if (success) {
recreate();
tvSender.setText("");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
MessageSender loginrequest = new MessageSender(message, username,username1, responselistener);
RequestQueue queue = Volley.newRequestQueue(ChatRoom.this);
queue.add(loginrequest);
}
});

There is no need to restart whole Activity. Instead you can insert an element in your list dataset(ArrayList<> or something) and call adapter.notifyDataSetChanged() to make the changes in listview.

Related

Volley no response from HTTP GET

I'm trying to retrieve the JSON from an API but I'm not getting anything.
The JSON :
{"coord":{"lon":90.41,"lat":23.71},"weather":[{"id":721,"main":"Haze","description":"haze","icon":"50n"}],"base":"stations","main":{"temp":25,"feels_like":28.6,"temp_min":25,"temp_max":25,"pressure":1011,"humidity":83},"visibility":3500,"wind":{"speed":1.5,"deg":90},"clouds":{"all":75},"dt":1588093825,"sys":{"type":1,"id":9145,"country":"BD","sunrise":1588029983,"sunset":1588076702},"timezone":21600,"id":1185241,"name":"Dhaka","cod":200}
I did add INTERNET permission :
<uses-permission android:name="android.permission.INTERNET" />
My code :
private void httpGet() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://api.openweathermap.org/data/2.5/weather?q=" + CITY + "&units=metric&appid=" + API;
//https://api.openweathermap.org/data/2.5/weather?q=dhaka,bd&units=metric&appid=5694263c8d821570bfccff2a13246a73
Log.d("TEST", "Fonction lancee 1/2" + url);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TEST", "Fonction lancee 3/2" + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("TEST", "Erreur");
}
});
queue.add(jsonObjectRequest);
}
I also tested with StringRequest with the same result, no response.
EDIT
My entire classe to see the context :
public class MainActivity extends AppCompatActivity {
TextView tempTxt;
String CITY = "dhaka,bd";
String API = "5694263c8d821570bfccff2a13246a73";
String url = "https://api.openweathermap.org/data/2.5/weather?q=" + CITY + "&units=metric&appid=" + API;
//https://api.openweathermap.org/data/2.5/weather?q=dhaka,bd&units=metric&appid=5694263c8d821570bfccff2a13246a73
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tempTxt = findViewById(R.id.tempTxt);
httpGet();
//new weatherTask().execute();
Log.d("TEST", "TEST OUT CALL");
Button button2 = findViewById(R.id.definirp);
button2.setOnClickListener(new View.OnClickListener() {
//Passer a la seconde Activity
public void onClick(View v) {
Intent activity2 = new Intent(getApplicationContext(), Activity2.class);
startActivity(activity2);
finish();
}
});
//Affichage de l'heure
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView theure = (TextView) findViewById(R.id.date);
TextView tdate = (TextView) findViewById(R.id.heure);
long date = System.currentTimeMillis();
//Format de l'heure
SimpleDateFormat sdfTime = new SimpleDateFormat("hh:mm:ss");
SimpleDateFormat sdfDate = new SimpleDateFormat("MMM dd yyyy");
String timeString = sdfDate.format(date);
String dateString = sdfTime.format(date);
theure.setText(timeString);
tdate.setText(dateString);
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
}
private void httpGet() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://api.openweathermap.org/data/2.5/weather?q=" + CITY + "&units=metric&appid=" + API;
//https://api.openweathermap.org/data/2.5/weather?q=dhaka,bd&units=metric&appid=5694263c8d821570bfccff2a13246a73
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
tempTxt.setText(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
tempTxt.setText("That didn't work!");
}
});
queue.add(stringRequest);
}
You can test the page of my JSON, the address is in comment in my code, (there is a comma in the city), it works.

when i am pressing back button(up button) it is showing "app stopped unfortunately" after using volley

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
but1=(Button)findViewById(R.id.btnlogin);
//
final String Token=getIntent().getExtras().getString("token");
// Toast.makeText(getApplicationContext(),Token, Toast.LENGTH_SHORT).show();
final String firstName=getIntent().getExtras().getString("firstname");
//getting cardview data's
String url =
com.android.volley.toolbox.JsonObjectRequest jsonRequest = new com.android.volley.toolbox.JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// the response is already constructed as a JSONObject!
try {
JSONArray obj = response.getJSONArray("result");
int o = obj.length();
Log.v("Length", String.valueOf(o));
for (int i = 0; i < obj.length(); i++) {
JSONObject jsonObject = obj.getJSONObject(i);
//listname.add(jsonObject.getString("templateId"));
listehr.add(jsonObject.getString("templateId"));
listdate.add(jsonObject.getString("startTime"));
listtime.add(jsonObject.getString("category"));
// ehrUid.add(jsonObject.getString("ehrUid"));
List<String> compositionUid = new ArrayList<>();
// String startTime = jsonObject.getString("startTime");
// Log.v("startTime",startTime);
}
Log.v("listtime", String.valueOf(listtime.size()));
Log.v("Response", response.toString());
String total = response.getString("total");
Log.v("Total",total);
String result = response.getString("result");
Log.v("Result",result);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println(error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization",Token);
return headers;
}
};
com.android.volley.toolbox.Volley.newRequestQueue(NavigationActivity.this).add(jsonRequest);
//
You have to send String Values for these two Keys "token","firstname".
final String Token=getIntent().getExtras().getString("token");
final String firstName=getIntent().getExtras().getString("firstname");
If you cant find it send the code snippet of intent in another class.
Punithapriya this is the code for main activity
public class MainActivity extends AppCompatActivity {
TextView t;
private EditText username;
private EditText password;
EditText showPsd;
CheckBox mCbShowPwd;
public Button but1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//login page using json
but1=(Button)findViewById(R.id.btnlogin);
username=(EditText)findViewById(R.id.editText2);
password=(EditText)findViewById(R.id.btnpass);
but1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//validation for login
if(username.getText().toString().length()==0){
username.setError("Username not entered");
username.requestFocus();
}
else if(password.getText().toString().length()==0){
password.setError("Password not entered");
password.requestFocus();
}
//
String url = ;
JsonObjectRequest jsonRequest = new JsonObjectRequest
(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// the response is already constructed as a JSONObject!
try {
Log.v("Hai", response.toString());
String firstName = response.getString("firstName");
Log.v("firstName", firstName);
String organizationList = response.getString("organizationList");
Log.v("organizationList",organizationList);
String token = response.getString("token");
Log.v("token",token);
Toast.makeText(getApplicationContext(),"Logged in Suceessfully", Toast.LENGTH_SHORT).show();
Intent i = new Intent(MainActivity.this,NavigationActivity.class);
i.putExtra("token",token);
i.putExtra("firstname",firstName);
startActivity(i);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println(error);
Toast.makeText(getApplicationContext(),"Login Error", Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(MainActivity.this).add(jsonRequest);
}
});
//password
showPsd = (EditText) findViewById(R.id.btnpass);
// get the show/hide password Checkbox
mCbShowPwd = (CheckBox) findViewById(R.id.btnshow);
// add onCheckedListener on checkbox
// when user clicks on this checkbox, this is the handler.
mCbShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// checkbox status is changed from uncheck to checked.
if (!isChecked) {
// show password
showPsd.setTransformationMethod(PasswordTransformationMethod.getInstance());
EditText et = (EditText)findViewById(R.id.btnpass);
et.setSelection(et.getText().length());
} else {
// hide password
showPsd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
EditText et = (EditText)findViewById(R.id.btnpass);
et.setSelection(et.getText().length());
}
}
});
//
//Textview calling
final TextView regLink=(TextView)findViewById(R.id.register1);
final TextView forLink=(TextView)findViewById(R.id.forgot);
//register
regLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent regIntent=new Intent(MainActivity.this,RegisterActivity.class);
MainActivity.this.startActivity(regIntent);
}
});
//forgot
forLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent forIntent=new Intent(MainActivity.this,ForgotActivity.class);
MainActivity.this.startActivity(forIntent);
}
});
}
//exit dialog box
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("EHR Store");
builder.setIcon(R.drawable.sd);
builder.setMessage("Do you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}

App stops working on S6 only

I have no idea whats going on here. My app works perfectly fine on the J5 and J6, but it stops working on the S6 (same android version on all phones)
And it only stops when I have the following code:
When I publish, android studio says 0 errors and 0 warnings
I'm still pretty new to android studio, and I've tried it with Thread myThread and without thread
public class IntroPage extends AppCompatActivity {
private ImageButton btnSkip;
private ImageButton btnUpdate;
// need this for post
RequestQueue requestQueue;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.intro_page);
requestQueue = Volley.newRequestQueue(getApplicationContext());
// outlets
btnSkip = (ImageButton) findViewById(R.id.btnSkip);
btnUpdate = (ImageButton) findViewById(R.id.btnUpdate);
// hide both on default
btnSkip.setVisibility(View.VISIBLE);
btnUpdate.setVisibility(View.GONE);
// when submit is clicked
btnSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent startMainScreen = new Intent(getApplicationContext(), MainActivity.class);
startActivity(startMainScreen);
finish();
}
});
// update
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=ddddddddd"));
startActivity(intent);
}
});
// get app version
PackageInfo pInfo = null;
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
String version = pInfo.versionName;
final Integer versionCode = pInfo.versionCode;
// conn
Thread myThread = new Thread() {
#Override
public void run() {
StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST,
"https://www.domain.com/appVersion.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responseJson = new JSONObject(response);
Log.i("JSON RESPONSE", responseJson.toString());
// check if we are up to date
if (responseJson.getInt("version") > versionCode) {
btnSkip.setVisibility(View.GONE);
btnUpdate.setVisibility(View.VISIBLE);
} else {
btnSkip.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
// This whole section can be deleted if we dont post vars
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<>();
parameters.put("club", "Murmur");
parameters.put("device", "Android");
return parameters;
}
};
jsonObjectRequest.setShouldCache(false);
// requestQueue.getCache().remove("https://www.domain.com/appVersion.php");
requestQueue.add(jsonObjectRequest);
}
};
myThread.start();
}
}

Android: checking database with volley library constantly

I started learning Android and Java a week ago and now I am trying to make an login application. I am using Volley libary to communicate with my server. I have done the login part. Now, what I want to do is to check the database every minute to see if the password or the username somehow changed. If the information in the database is changed, app will automaticly logout the user.
If you can explain which tools(Services,BroadcastReceivers) I can use and how can I achieve it, as I am not very experienced.
This is what I tried and failed:
loginChecker.class
public class loginChecker extends Service {
public loginChecker() {
}
public static String username;
public static String password;
private loginChecker mInstance = this;
public static boolean loginCheck= true;
public static String responseG = "failed";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle b=intent.getExtras();
username = b.getString("username");
password = b.getString("password");
final String URL = ".........";
final RequestQueue requestQueue = Volley.newRequestQueue(mInstance);
new Thread(new Runnable(){
public void run() {
do{
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
responseG = response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
responseG = "error";
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("username", username);
hashMap.put("password", password);
return hashMap;
}
};
requestQueue.add(request);
switch(responseG){
case "successful" :
loginCheck = true;
break;
case "failed" :
loginCheck= false;
break;
case "error" :
loginCheck = false;
break;
}
}
while(loginCheck == true || responseG == "successful");
}
}).start();
Toast.makeText(getApplicationContext(), "LOOP ENDED", Toast.LENGTH_SHORT).show();
return START_REDELIVER_INTENT;
}
#Override
public void onDestroy() {
final Intent mainActivity = new Intent(mInstance, MainActivity.class);
mainActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mainActivity);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity {
private RequestQueue requestQueue;
private static final String URL = "........";
private StringRequest request;
private TextView text;
private EditText userName, passWord;
private Button loginButton;
public MainActivity mInstance = this;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView);
userName = (EditText) findViewById(R.id.userName);
passWord = (EditText) findViewById(R.id.passWord);
loginButton = (Button) findViewById(R.id.loginButton);
requestQueue = Volley.newRequestQueue(this);
final Intent profilePage = new Intent(this, Profile.class);
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick (View v){
loginButton.setEnabled(false);
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
text.setText(response);
switch(response){
case "successful" :
Intent loginCheckerService = new Intent(mInstance, com.erenyenigul.apps.starter.services.loginChecker.class);
Bundle b = new Bundle();
b.putString("username", String.valueOf(userName.getText()));
b.putString("password", String.valueOf(passWord.getText()));
loginCheckerService.putExtras(b);
startService(loginCheckerService);
startActivity(profilePage);
finish();
break;
case "failed" :
Toast.makeText(getApplicationContext(), "Username or Password you entered is wrong!", Toast.LENGTH_LONG).show();
loginButton.setEnabled(true);
break;
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "There is a problem with our servers or you don't have internet connection!", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("username", userName.getText().toString());
hashMap.put("password", passWord.getText().toString());
return hashMap;
}
};
requestQueue.add(request);
}
}
);
}
}
There is also a file called Profile.class but it is empty. I tried this but the loop lasted one tour. It stopped even though the connection was ok and the data wasn't changed.

Listview not updated in android after spinner selection

hello guys i am working an app where i want to update my listview but everything is working perfect only list view is not updated i don't understand where i am doing wrong help me
code is
public class MainActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener{
private Spinner spinner;
private ArrayList<String> students;
private JSONArray result;
CallbackManager callbackManager;
ShareDialog shareDialog;
// listveiw data
private static final String TAG = MainActivity.class.getSimpleName();
String url = "http://www.example.com/json/json.php";
private ProgressDialog pDialog;
private List<Model> movieList = new ArrayList<Model>();
private ListView listView;
private CustomListAdapter adapter;
final Model model = new Model();
final Json_Data j_data = new Json_Data();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
students = new ArrayList<String>();
spinner = (Spinner) findViewById(R.id.txtSpinner);
listView = (ListView) findViewById(R.id.list);
spinner.setOnItemSelectedListener(this);
getData();
listdata();
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final TextView tv_id = (TextView) view.findViewById(R.id.title);
String txt = tv_id.getText().toString();
model.setItemText(txt);
Log.e(TAG, "====>" + txt);
_Dialog_Custom();
}
});
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
}
public void listdata(){
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
hidePDialog();
Log.e(TAG, response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Model model = new Model();
String status = obj.getString("txt");
String cate = obj.getString("category");
model.setList_category(cate);
model.setTitle(status);
movieList.add(model);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
}
private void getData() {
StringRequest stringRequest = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j_obj = null;
try {
j_obj = new JSONObject(response);
result = j_obj.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void getStudents(JSONArray j) {
for (int i = 0; i < j.length(); i++) {
try {
JSONObject json = j.getJSONObject(i);
students.add(json.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, students));
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text_spinner = spinner.getSelectedItem().toString();
//Log.e("Selected value in","==>"+text_spinner);
j_data.setSpintext(text_spinner);
makeJsonArrayRequest();
Toast.makeText(MainActivity.this, "Get Value from spinner" +text_spinner, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
private void _Dialog_Custom() {
final Dialog dialog = new Dialog(this);
final String txt1 = model.getItemText().toString();
Log.e("Hello Dialog", ":=>" + txt1);
dialog.setContentView(R.layout.dialogbox);
dialog.setTitle("Share via");
dialog.setCanceledOnTouchOutside(true);
ImageButton _Fb_Sharebtn = (ImageButton) dialog.findViewById(R.id.share_facebook);
_Fb_Sharebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ShareDialog.canShow(ShareLinkContent.class)) {
// https://developers.facebook.com/docs/sharing/android
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentTitle("Hello Facebook")
.setContentDescription(
"The 'Hello Facebook' sample showcases simple Facebook integration")
.setContentUrl(Uri.parse("http://developers.facebook.com/android"))
.build();
shareDialog.show(linkContent);
}
}
});
ImageButton _Sharebtn_google = (ImageButton) dialog.findViewById(R.id.share_btn_google);
_Sharebtn_google.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent shareIntent = new PlusShare.Builder(MainActivity.this)
.setType("text/plain")
.setText(txt1)
.getIntent();
try {
startActivity(shareIntent);
} catch (ActivityNotFoundException ex) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.google.android.apps.plus&hl=en")));
}
}
});
ImageButton whtsapp_sahre = (ImageButton) dialog.findViewById(R.id.whatsapp_btn);
whtsapp_sahre.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
whatsappIntent.setType("text/plain");
whatsappIntent.setPackage("com.whatsapp");
String result = txt1;
whatsappIntent.putExtra(Intent.EXTRA_TEXT, result);
try {
startActivity(whatsappIntent);
} catch (ActivityNotFoundException ex) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.whatsapp")));
}
}
});
ImageButton _Twwiterbtn = (ImageButton) dialog.findViewById(R.id.twwiter_btn);
_Twwiterbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
String result = txt1;
intent.setType("text/plain")
.setPackage("com.twitter.android");
intent.putExtra(Intent.EXTRA_TEXT, result);
try {
startActivity(intent);
} catch (ActivityNotFoundException ex) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.twitter.android&hl=en")));
}
}
});
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
}
});
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
}
});
dialog.show();
}
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent backintent = new Intent(getApplicationContext(), Main_Selected_Activity.class);
startActivity(backintent);
finish();
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
private void makeJsonArrayRequest() {
String spinner_data =j_data.getSpintext().toString().trim();
Log.e(TAG, spinner_data.toString());
String arrayurl = "http://www.example.com/jsoncategory.php?category="+spinner_data;
Log.e("Link is here","==>"+arrayurl);
ArrayList<String> newdata = new ArrayList<String>();
movieList = new ArrayList<Model>();
JsonArrayRequest movieReq = new JsonArrayRequest(arrayurl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e(TAG, "link response=>" + response);
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
String name = obj.getString("txt");
model.setList_category(name);
movieList.add(model);
}catch (JSONException e) {
e.printStackTrace();
Log.e("Hello error","==>"+e);
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
}
}
please help me
Follow The Below approach
Create a public method in your adapter class:
private List<Model> adapterInitialMovieList = null;
public void setDataOnSpinnerSelected(List<Model> movieList){
adapterInitialMovieList = movieList;
notifyDataSetChanged();
}
In Your Activity Class Inside Spinner onClick method:
if(adapter != null){
adapter.setDataOnSpinnerSelected(yourChangedArrayListOfModelClass);
}
use
movieList.clear();
instead of
movieList = new ArrayList<Model>();
The problem is about the creation of a new arraylist. So, the ArrayAdapter do not 'know' you when you want to create a new one ArrayList (with the different address).
In line
adapter = new CustomListAdapter(this, movieList);
you push a some address of arraylist. In a new line later you generates a new arraylist with the different one and work with it. But the adapter works with the 'old variant' of arraylist.
Remove this line from makeJsonArrayRequest() :
movieList = new ArrayList<Model>();
You are assigning a new object(ArrayList) to the movieList and adding values in the new object instead of the one which you passed to the list adapter. Hence the reference of the object which is being used by the list adapter is lost and when you call adapter.notifyDataSetChanged(); there is no updation as the object which is used by the list adapter is unchanged.

Categories

Resources