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();
}
}
Related
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btn;
TextView price;
String url = "https://koinim.com/ticker/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.btn_get_information);
price = (TextView)findViewById(R.id.price);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v){
if (v.getId() == R.id.btn_get_information){
JsonObjectRequest jsonObjectRequest = new
JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
price.setText("BTC: " +
response.getString("sell")+ " " + "₺" );
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText((getApplicationContext()),"Error",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
MySingleton.getmInstance(getApplicationContext()).
addToRequestQue(jsonObjectRequest);
}
}
}
I am a new developer in android.
I looked at the sources and made the parse from one link. But I have four links. How do I parse the four links?
Instead of having a String url, create an ArrayList of Strings that holds all your URLs.
In the method onClick() loop through the URLs.
Note that the ArrayList is filled in onCreate. I also added a try/catch clause in onClick, so if something goes wrong with one URL, the others will be parsed anyways.
Handling different URLs:
For parsing the Koinim ticker, you needed the key "sell", for Paribu you will need "last".
In the loop I am checking if the URL contains either Koinim or Paribu and adjust they key accordingly.
ArrayList<String> urls = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn_get_information);
price = (TextView) findViewById(R.id.price);
urls.add("https://koinim.com/ticker/");
urls.add("url2");
urls.add("url3");
urls.add("url4");
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_get_information) {
for (String url : urls) {
try {
JsonObjectRequest request = null;
if(url.contains("koinim"))
{
request = getSellPrice("sell");
}
else if(url.contains("paribu"))
{
request = getSellPrice("last");
}
if(request != null)
{
MySingleton.getmInstance(getApplicationContext()).
addToRequestQue(jsonObjectRequest);
}
} catch (Exception ex) {
// something went wrong, handle exception here
}
}
}
}
private JsonObjectRequest getSellPrice(String key)
{
JsonObjectRequest jsonObjectRequest = new
JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
price.setText("BTC: " +
response.getString(key) + " " + "₺");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText((getApplicationContext()), "Error", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
return jsonObjectRequest;
}
I'm trying to make a volley request when I receive LocalBroadcast message. But I'm getting this RuntimeException. I tried using thread but still getting the same error. Should I use something else? I'm getting the exception in the method prepareData() that's why I added try/catch inside it. In this try/catch I'm getting the exception.
public class NewItemsNearUFragment extends Fragment{
private SharedPref pref;
private ConnectionDetector cd;
private ProgressDialog pd;
private LocalBroadcastManager bManager;
Activity activity;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
pref = new SharedPref(getActivity());
cd = new ConnectionDetector(getActivity());
pd = new ProgressDialog(getActivity());
bManager = LocalBroadcastManager.getInstance(getActivity());
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("UPDATE_NOTIFY");
bManager.registerReceiver(bReceiver, intentFilter);
}
#Override
public void onDestroy() {
LocalBroadcastManager.getInstance(activity).unregisterReceiver(bReceiver);
super.onDestroy();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Activity){
activity=(Activity) context;
}
}
private BroadcastReceiver bReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent!=null){
if(intent.getAction().equals("UPDATE_NOTIFY")) {
System.out.println("sammy_received_broadcast");
new Thread() {
public void run() {
try {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
prepareData();
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}
}
};
private void prepareData(){
try{
pd.setMessage(activity.getString(R.string.plzwait));
pd.show();
if(arrayList!=null )arrayList.clear();
if(TextUtils.isEmpty(pref.getString(Utility.HOME_LAT)))
pref.setString(Utility.HOME_LAT, String.valueOf(GPSTracker.currLat));
if(TextUtils.isEmpty(pref.getString(Utility.HOME_LANG)))
pref.setString(Utility.HOME_LANG, String.valueOf(GPSTracker.currLong));
if(TextUtils.isEmpty(pref.getString(Utility.HOME_PRICEORDER)))
pref.setString(Utility.HOME_PRICEORDER, "");
if(TextUtils.isEmpty(pref.getString(Utility.HOME_DATAORDER)))
pref.setString(Utility.HOME_DATAORDER, "");
if(TextUtils.isEmpty(pref.getString(Utility.HOME_PRODNAME)))
pref.setString(Utility.HOME_PRODNAME, "");
if(TextUtils.isEmpty(pref.getString(Utility.HOME_CATID)))
pref.setString(Utility.HOME_CATID, "");
if(TextUtils.isEmpty(pref.getString(Utility.HOME_STARTPRICE)))
pref.setString(Utility.HOME_STARTPRICE, "");
if(TextUtils.isEmpty(pref.getString(Utility.HOME_ENDPRICE)))
pref.setString(Utility.HOME_ENDPRICE, "");
StringRequest stringRequest = new StringRequest(Request.Method.POST, Utility.ALLPROD,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pd.dismiss();
System.out.println("sammy_All_Prod_response "+response);
try {
JSONObject jObj = new JSONObject(response);
if(jObj.getInt("ACK")==1){
JSONArray jsonArray = jObj.getJSONArray("all_products");
for(int i=0;i<jsonArray.length();i++){
JSONObject main = jsonArray.getJSONObject(i);
Model home = new Model();
home.setUserid(main.getString("user_id"));
home.setTitle(main.getString("name"));
String price = "$"+main.getString("price");
home.setPrice(price);
home.setImage(main.getString("image"));
home.setPrdid(main.getString("product_id"));
arrayList.add(home);
}
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.dismiss();
if (error instanceof TimeoutError) {
Toast.makeText(getActivity(),getString(R.string.tooslow),Toast.LENGTH_LONG).show();
}else if (error instanceof NoConnectionError){
Toast.makeText(getActivity(),getString(R.string.nointernet),Toast.LENGTH_LONG).show();
}else if (error instanceof AuthFailureError) {
System.out.println("sammy_AuthFailureError "+error);
} else if (error instanceof ServerError) {
System.out.println("sammy_ServerError "+error);
} else if (error instanceof NetworkError) {
System.out.println("sammy_NetworkError "+error);
} else if (error instanceof ParseError) {
System.out.println("sammy_ParseError "+error);
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", pref.getString(Utility.USERID));
params.put("user_lat", pref.getString(Utility.HOME_LAT));
params.put("user_lang", pref.getString(Utility.HOME_LANG));
params.put("price_order", pref.getString(Utility.HOME_PRICEORDER));
params.put("data_order", pref.getString(Utility.HOME_DATAORDER));
params.put("product_name", pref.getString(Utility.HOME_PRODNAME));
params.put("categoryid", pref.getString(Utility.HOME_CATID));
params.put("start_price", pref.getString(Utility.HOME_STARTPRICE));
params.put("end_price", pref.getString(Utility.HOME_ENDPRICE));
System.out.println("sammy_All_Prod_params "+params);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(activity.getApplicationContext());
//if(getActivity()!=null)
requestQueue.add(stringRequest);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}catch(Exception e){
System.out.println("sammy_prepareData_exception "+e);
}
}
}
Your mistake is you are calling prepareData(); inside thread
where in prepareData() function you are doing UI operation. Showing Toast , progressDialog etc.
Toast needs an Activity to show to the user interface and threads don't have that.
you should use UI thread instead:
getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getActivity(), "Message", Toast.LENGTH_LONG).show();
}
});
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.
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.
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.